Skip to main content
Logo image

Section 5.3 Basic loop algorithms

Now that we have the basics of if statements and for and while loops under our belts, weโ€™re ready to implement some actual algorithms. There are quite a few algorithms we can build out of a single loop with an occasional if inside the body of the loop. In later units we will apply these ideas to to data types like String, arrays, ArrayList which contain multiple elements and are naturally processed with loops. But in this section we will stick with loops dealing with the data types weโ€™ve already learned, mostly int and double.
Weโ€™ll start with algorithms for counting, summing, and averaging sequences of numbers. Then weโ€™ll look at finding the minimum and maximum values within a sequence of numbers. And finally weโ€™ll take apart an int value, using a loop to extract the individual digits.

Subsection 5.3.1 Summing and counting

Lots of loop algorithms use an accumulator pattern to accumulate some kind of value by updating a variable each time the loop body runs. The value of the accumulator variable when the loop is complete is the result the algorithm is intended to compute. If youโ€™ve ever counted on your fingers you already understand the basic idea. In this section weโ€™ll apply the accumulator pattern to summing, counting, and averaging algorithms.
The accumulator pattern has three parts:
  1. An accumulator variable that is initialized before the loop.
  2. A loop that loops sum number of times to produce the values we want to distill into our accumulator variable.
  3. Code in the body that updates the accumulator variable in some way.
Note, the accumulator variable is different than the loop variable that controls the loop itself; this is a variable that is going to hold the eventual answer we are trying to compute such as a count or a sum.
Letโ€™s start with a really simple example. This loop calculates the sum of the numbers from one to one hundred. The variable sum is the accumulator variable while i is the loop variable.
int sum = 0;
for (int i = 1; i <= 100; i++) {
    sum += i;
}
System.out.println("The sum of 1 through 100 is " + sum);
The first line initializes the accumulator variable sum to 0. In general we should initialize the variable to the value that would be the right answer if the loop didnโ€™t run at all. That is, if instead of adding up one hundred numbers we were adding up no numbers at all, what would the sum be? Zero. So thatโ€™s our initial value.
Then each time through the loop, sum is incremented by the current value of i and as a result when the loop ends sum is the total we want.
For the next few examples, letโ€™s assume we are working in a program for anayzing rainfall data in which we have a method nextMeasurement() which every time it is called returns a double representing an amount of rainfall per hour from some sequence of data.
We can implement a summing loop to get the total rainfall from the next dayโ€™s worth of hourly measurements:
double total = 0;
for (int i = 0; i < 24; i++) {
    total += nextMeasurement();
}
System.out.println(total + " cm of total rainfall.");
A loop for counting is similar to a summing loop, but instead of adding up values, it counts how many times through the loop the value meets some criteria. For instance, suppose we wanted to count how many hours we measured more than twelve centemeters of rain.
int count = 0;
for (int i = 0; i < 24; i++) {
    if (nextMeasurement() > 12.0) {
        count++;
    }
}
System.out.println(total + " hours with over 12.0 cm of rainfall.");
If we compare this loop to the summing loop we can see the two key difference between summing and counting: when counting we only increase the accumulator by one each time, usually with ++, and we use an if to decide when to update it at all. For instance, this loop looks at all the measurements from a twenty-four hour period but only counts the ones that satisfy the criteria. Finally, the accumulator when weโ€™re counting is typically an int since we donโ€™t need any fractional parts while in a summing loop in might be an int or a double, depending on what the values weโ€™re summing are.
On the AP exam, they often will provide a method to call to get a boolean that determines whether something should be counted or not. For instance, continuing the theme of previous example, they might provide a method, extraRainy, that takes a measurement and returns true if it qualifies as extra rainy and should be counted. To use such a method, just call it in the condition of the if:
int count = 0;
for (int i = 0; i < 24; i++) {
    if (extraRainy(nextMeasurement())) { // change the condition to use the provided method
        count++;
    }
}
System.out.println(total + " extra rainy hours.");

Subsection 5.3.2 Averaging

Averaging isnโ€™t really its own separate loop pattern. Since the average of a set of values is the sum of the values divided by the count, we just need to combine summing and counting. And in a simple average computation we donโ€™t even need to count the values separately because we may know how many there are. For instance hereโ€™s a loop to get the average rainfall in a day:
double total = 0;
for (int i = 0; i < 24; i++) {
    total += nextMeasurement();
}
System.out.println("Average rainfall: " + total / 24);
But if we wanted to do something more complicated like getting the average of just the hours with more than twelve centemeters of rainfall, we could combine the summing and counting patterns:
double total = 0;
int count = 0;
for (int i = 0; i < 24; i++) {
    double m = nextMeasurement();
    if (m > 12.0) {
        total += nextMeasurement();
        count++;
    }
}
System.out.println("Average rainfall in rainy hours: " + total / count);
Try the accumulator practice below.

Activity 5.3.1.

Complete the methods below to compute the sum and average of a set of numbers.
We can also use a while loop to calculate the average of an arbitrary number of numbers given to us as input from the user. Intead of a loop that runs a specific number of times, the loop runs as long as the number provided by the user is not -1.
// 1. initialize the loop variable (get the first number)
System.out.print("Please enter a number to average in or -1 to stop: ");
number = scan.nextInt();

// 2. test the loop variable (against sentinel value)
while (number != -1)
{
  sum += number; // add number to sum
  count++; // count the number
  // 3. Update the loop variable (get a new number)
  System.out.print("Please enter a number to average in or -1 to stop: ");
  number = scan.nextInt();
}
System.out.println(count);
// calculate average
average = (double) sum/count;
System.out.println("The average is " + average);
You can try this below on the input numbers below the code or for more interactive input, try it in your own IDE online with JuiceMind or replit.

Activity 5.3.2.

Try the code below with an input-controlled loop that prints out the numbers entered by the user until -1 is entered. Then, change it to calculate the sum and average of the numbers entered.

Subsection 5.3.3 Finding minimums and maximums

Another variation of the accumulator pattern is a loop that updates the accumulator with the value returned by some method that takes the current value of the accumulator and the new value in each iteration. Two commonly used methods in this pattern are Math.min and Math.max that we discussed in Sectionย 3.3ย The Math class. This is a very common pattern in the AP exam for FRQ #1.
To determine the minimum or maximum value in a sequence of numbers, use a variable to store the current minimum or maximum value. Use a loop to go through the sequence of numbers and update the minimum or maximum value by calling either Math.min or Math.max. For example, this loop chooses ten random numbers and finds the minimum value among them.
int min = Integer.MAX_VALUE;
for (int i = 0; i < 10; i++) {
    int num = (int) (Math.random() * 100);
    min = Math.min(min, num);
}
System.out.println("The minimum value is " + min);
If didnโ€™t remember about the Math.min method, you could always implement the logic yourself with an if statement:
int min = Integer.MAX_VALUE;
for (int i = 0; i < 10; i++) {
    int num = (int) (Math.random() * 100);
    if (num < min) {
        min = num;
    }
}
System.out.println("The minimum value is " + min);
That code works essentially the same way with the very sight difference that the first version always assigns a value to min but sometimes itโ€™s the current value and in the second version we only assign to min when weโ€™ve actually found a smaller value. Either way is fine though avoiding if statements that we donโ€™t need often leads to clearer code.

Activity 5.3.3.

Run to see the min method in action. Then, complete the max method to find the maximum of a set of random numbers. (Bonus question: after youโ€™ve correctly implemented max, is it possible that the program will report a minimum value that is larger than the maximum value?)

Subsection 5.3.4 Exctacting digits with % and /

In the previous examples we were using numbers to control our loops and as the values to be summed, counted, averaged, minimized, and maximized. In this section weโ€™ll use a while loop to take apart an int into its individual digits.
Before we got to the loop part of this problem there are two key facts to keep in mind about some arithmetic operators we first talked about in Sectionย 2.3ย Arithmetic expressions. First off, we need to realize that to get the rightmost digit of any int value is the remainder when divided by ten. For example 1234 % 10 โŸน 4. Second, dividing an int value by ten effectively throws away the rightmost digit because of truncation. 1234 / 10 โŸน 123. Also note, that if we divide an int value less than ten by ten, we get 0 after the last digit is thrown away: 9 / 10 โŸน 0.
Putting those facts together, we can outline a while loop that we can use to extract the digits from a positive int from right (oneโ€™s place) to left:
while (n > 0) { // i.e. n still has at least one non-0 digit
    int d = n % 10;
    n /= 10;
    // Do something with d
}
We could use a loop like this to do anything we want with the digits of a number: reverse them, add them up, or check if the number contains a certain digit. The last one is your goal in the next exercise.

Activity 5.3.4. Check for specific digit.

Complete the checkDigit method below to determine if a positive number contains a given single-digit number as one of its digits.

Subsection 5.3.5 Summary

  • (AP 2.9.1) There are standard algorithms to:
    1. Identify if an integer is or is not evenly divisible by another integer
    2. Identify the individual digits in an integer
    3. Determine the frequency with which a specific criterion is met
    4. Determine a minimum or maximum value
    5. Compute a sum or average
  • The accumulator pattern is an algorithm that involves storing and updating an accumulator value within a loop, for example to compute a sum or average of a set of values.
  • A common algorithm pattern is an if statement within a loop to test each value against a criterion, such as finding the minimum or maximum value in a sequence of numbers.
You have attempted of activities on this page.