Activity 5.3.1.
Complete the methods below to compute the sum and average of a set of numbers.
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 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.
int value, using a loop to extract the individual digits.
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);
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.
sum is incremented by the current value of i and as a result when the loop ends sum is the total we want.
nextMeasurement() which every time it is called returns a double representing an amount of rainfall per hour from some sequence of data.
double total = 0;
for (int i = 0; i < 24; i++) {
total += nextMeasurement();
}
System.out.println(total + " cm of total rainfall.");
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.");
++, 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.
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.");
double total = 0;
for (int i = 0; i < 24; i++) {
total += nextMeasurement();
}
System.out.println("Average rainfall: " + total / 24);
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);
// 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);
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.
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);
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);
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.
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?)
while loop to take apart an int into its individual digits.
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.
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
}
checkDigit method below to determine if a positive number contains a given single-digit number as one of its digits.