A handful of loop patterns do most of the work in Java: an accumulator for a sum or a count, a running best for a minimum or maximum, % 10 and / 10 to take an int apart digit by digit, and a boolean flag to check whether all or any values pass a test. Each pattern sets a variable before the loop, updates it inside the loop, and uses it after the loop ends.
Quick check
In Java, what is 17 % 5?Show answerHide answer
%gives the remainder, and 17 = 3 × 5 + 2.
In Java, what is 17 / 5 when both values are int?Show answerHide answer
- Dividing two
intvalues truncates toward zero, so the 0.4 is dropped.
- Dividing two
What does 4072 % 10 give, and why is that useful?Show answerHide answer
2, the last digit. Dividing by 10 leaves the last digit as the remainder, which is how a loop can pick off digits one at a time.
Know these already? Jump to the practice questions
What you'll be able to do
- Determine what a loop that builds a sum, a count or an average produces, and explain why the average needs a cast.
- Choose a safe starting value for a running minimum or maximum.
- Calculate what a loop using
% 10and/ 10produces from an int's digits. - Decide how a
booleanflag or an earlyreturnanswers an "all" or "any" question.
Key terms
Accumulator
A variable that starts at 0 before a loop and has each value added to it inside the loop.
- In plain English
- A running total.
- Don't write
- "Declare
sum = 0inside the loop."
Counter
A variable that starts at 0 and goes up by 1 each time a value meets a condition.
- In plain English
- A tally of the values that pass a test.
- Don't write
- "A counter adds the values it counts."
Flag
A boolean variable that records whether something has happened yet during a loop.
- In plain English
- A yes/no marker you set when you find what you are looking for.
- Don't write
- "Set the flag back to
falsewhenever a value fails." (That undoes an "any" search.)
How do you find a sum, a count and an average?
Declare the variable before the loop, update it inside, and read it after. This counter tallies the multiples of 3 from 1 to 20:
int count = 0;
for (int k = 1; k <= 20; k++)
{
if (k % 3 == 0)
{
count++;
}
}
k % 3 == 0 is true for 3, 6, 9, 12, 15 and 18, so count ends at 6. For a sum, replace count++ with sum += k, where sum starts at 0.
An average divides an int sum by an int count, and sum / count truncates, so cast first: (double) sum / count converts sum before the division. With sum = 10 and count = 4, sum / count is 2 but (double) sum / count is 2.5. Casting and integer division are Java syntax, not on the Java Quick Reference: Learn this.
Check yourself
Show answerHide answer
4: the values 7, 14, 21 and 28.
How do you find a minimum or a maximum?
Keep a running best. Start it at a value every real value can beat, compare each new value with it, and replace it when the new one is better.
int max = Integer.MIN_VALUE;
for (int k = 1; k <= 6; k++)
{
int v = (k * 7) % 10;
if (v > max)
{
max = v;
}
}
The values of v are 7, 4, 1, 8, 5 and 2. max becomes 7, later 8, and ends at 8. Integer.MIN_VALUE is the smallest int, so any first value replaces it; it is on the Java Quick Reference. For a minimum, start at Integer.MAX_VALUE and use <. Starting at the first value also works.
Key idea
Never start a maximum at 0 unless every value is sure to be 0 or more.
Check yourself
Show answerHide answer
- Every value from -9 to -5 is below 0, so none replaces it; the true maximum is -5.
How do you take an int apart digit by digit?
For a positive int n, n % 10 is its last digit and n / 10 removes that digit, because int division drops the remainder. So 4072 % 10 is 2 and 4072 / 10 is 407. A loop repeats this until n reaches 0:
int n = 4072;
int digits = 0;
while (n > 0)
{
digits++;
n = n / 10;
}
n goes 407, 40, 4, 0, so digits ends at 4. The loop destroys n, so work on a copy if you need the number later. These loops assume n is positive: in Java, -47 % 10 is -7, because the remainder takes the sign of the left operand.
Check yourself
Show answerHide answer
8 and 95.
How do you check whether all or any values pass a test?
For "any", a flag starts false and becomes true as soon as one value passes. For "all", it starts true and becomes false as soon as one value fails. Nothing in the loop sets it back.
boolean found = false;
for (int d = 2; d < 91; d++)
{
if (91 % d == 0)
{
found = true;
}
}
found ends true, because 7 divides 91, so 91 has a divisor other than 1 and itself. Inside a method you can stop early: return true; at the first pass for "any", or return false; at the first failure for "all", with the other return after the loop.
Check yourself
Show answerHide answer
7, the only odd digit. The flag then stays false.
Worked example 1: Add the digits of a number
Question: What is printed when this code segment runs?
int n = 4072;
int sum = 0;
while (n > 0)
{
int d = n % 10;
sum += d;
n = n / 10;
}
System.out.println(sum);
What tells you the method
% 10 and / 10 in a while (n > 0) loop: trace one row per pass.
Step 1: Trace each pass.
Pass dsumnafter the pass1 2 2 407 2 7 9 40 3 0 9 4 4 4 13 0 WhyEach pass takes the last digit with
% 10, adds it, then removes it with/ 10.Step 2: Stop when the condition fails.
After pass 4,
nis 0, son > 0is false and the loop ends withsumat 13.WhyThe condition is checked before each pass.
Check it
4 + 0 + 7 + 2 = 13, and the loop ran 4 times, once per digit.
Answer
13
Worked example 2: Average without losing the decimal
Question: What is printed when this code segment runs?
int sum = 0;
int count = 0;
for (int k = 1; k <= 12; k++)
{
if (k % 3 == 0)
{
sum += k;
count++;
}
}
double avg = (double) sum / count;
System.out.println(sum / count + " " + avg);
What tells you the method
Two divisions, one with a cast: trace the accumulators, then check each division's types.
Step 1: Trace the accumulators.
The multiples of 3 are 3, 6, 9 and 12, so
sumis 30 andcountis 4.WhyOnly values with
k % 3 == 0reach the two updates.Step 2: Evaluate the two divisions.
sum / countis 30 / 4 with twointvalues, which is 7.(double) sum / countis 30.0 / 4, which is 7.5.WhyInteger division drops the remainder; casting
sumfirst makes it adoubledivision.Step 3: Build the printed text.
7 + " "is the string "7 ", then+ avgadds 7.5.WhyOnce one operand of
+is a String,+joins text.
Check it
7 × 4 = 28, which leaves remainder 2, and 2 / 4 = 0.5 is exactly the part the int division lost.
Answer
7 7.5
Worked example 3: Complete an "all" check
Question: The method should return true when every digit of the positive int n is odd, and false otherwise.
public static boolean allDigitsOdd(int n)
{
while (n > 0)
{
/* missing code */
n = n / 10;
}
return true;
}
Which code can replace /* missing code */?
- A)
if (n % 10 % 2 == 1) { return true; } - B)
if (n % 10 % 2 == 0) { return false; } - C)
if (n / 10 % 2 == 0) { return false; } - D)
if (n % 10 % 2 == 1) { return false; }
What tells you the method
An "all" check with return true; after the loop, so the loop must return false at the first digit that fails.
Step 1: Pick test inputs.
Use 135 (should be
true) and 241 (should befalse).WhyOne input that passes and one that fails catch most wrong options.
Step 2: Trace each option.
A returns
trueat the 5 of 135 and at the 1 of 241, so it is wrong on 241. B finds no even digit in 135 and returnstrue; in 241 it reaches the 4 and returnsfalse. C testsn / 10, the digits to the left: on the third pass for 135,n / 10is 0, which is even, so it wrongly returnsfalse. D returnsfalseat the 5 of 135.Whyn % 10is the current last digit, and% 2 == 0means even.
Check it
Try B on 3: the only digit is odd, so the loop ends and return true; runs, which is correct.
Answer
B
Your turn
Question: What is printed when this code segment runs?
int low = Integer.MAX_VALUE;
int at = 0;
for (int k = 1; k <= 6; k++)
{
int v = (k * 7) % 10;
if (v < low)
{
low = v;
at = k;
}
}
System.out.println(low + " at " + at);
Step 1: List the values of
v.For
k= 1 to 6 they are 7, 4, 1, 8, 5 and 2.Step 2: Your go: trace
lowandatthrough the six passes.
Show the full solutionHide the solution
Step 2. At k = 1, 7 is less than Integer.MAX_VALUE, so low is 7 and at is 1. At k = 2, 4 < 7, so low is 4 and at is 2. At k = 3, 1 < 4, so low is 1 and at is 3. The values 8, 5 and 2 are not less than 1, so nothing else changes.
Answer: 1 at 3
Traps
Trap
Starting max at 0 works for any values.
It seems right because a sum starts at 0. But if every value is negative, none beats 0 and the result is 0, which is not one of the values. Start at Integer.MIN_VALUE or at the first value.
Values are -3, -8 and -1. What does a max that starts at 0 report, and what is the true maximum?
It reports 0; the true maximum is -1.
Trap
double avg = sum / count; stores the exact average.
It seems right because avg is a double. But the right side is worked out first, with two int values, so the decimal part is dropped before the result is stored. Write (double) sum / count.
With int sum = 9 and int count = 2, what does double avg = sum / count; store?
4.0. 9 / 2 is 4, and 4 is then stored as 4.0.
What's examined
On the AP® Computer Science A exam (Unit 2: Selection and Iteration), these patterns sit inside multiple-choice questions that ask what a segment prints or returns, or which code completes a method. In free response you write your own Java, where the same patterns can be useful.
Practice questions
- Recall
sumandcountareintvariables. Which expression gives their exact average as adouble?
- A)
sum / count - B)
(double) (sum / count) - C)
(double) sum / count - D)
sum / count * 1.0
Show answer
Answer: C. The cast makes sum a double before dividing, so the decimal part is kept.
Why the others are wrong:
- A divides two
intvalues, so the decimal part is dropped. - B casts after the
intdivision has already truncated. - D multiplies by 1.0 after the truncating division.
- Apply What is printed when this code segment runs?
int count = 0;
for (int k = 10; k <= 30; k++)
{
if (k % 4 == 0 || k % 6 == 0)
{
count++;
}
}
System.out.println(count);
Show answer
Answer: 7
Marking points:
- Multiples of 4: 12, 16, 20, 24, 28. Multiples of 6: 12, 18, 24, 30.
- 12 and 24 are in both lists but each
kis counted once, so the count is 7, not 9.
- Apply What value does
revhold after this code segment runs?
int n = 1250;
int rev = 0;
while (n > 0)
{
rev = rev * 10 + n % 10;
n = n / 10;
}
Show answer
Answer: 521
Marking points:
revgoes 0, 5, 52, 521 asngoes 125, 12, 1, 0.- The trailing 0 of 1250 adds nothing to
rev, so the result has three digits.
- Exam-style The method should return the average of the integers from
atobinclusive, soaverageOfRange(1, 4)should return 2.5.sumandcountmust stayintvariables, and only one line may change. Give the number of the line that stops it working.
1: public static double averageOfRange(int a, int b)
2: {
3: int sum = 0;
4: for (int k = a; k <= b; k++)
5: {
6: sum += k;
7: }
8: int count = b - a + 1;
9: return sum / count;
10: }
Show answer
Answer: Line 9.
Marking points:
sumis 10 andcountis 4, but10 / 4isintdivision, so the method returns 2.0.- Changing line 9 to
return (double) sum / count;returns 2.5.
- Exam-style What is printed when this code segment runs?
boolean found = false;
int k = 1;
while (k <= 20 && !found)
{
if (k * k > 50)
{
found = true;
}
k++;
}
System.out.println(k);
- A) 7
- B) 8
- C) 21
- D) 9
Show answer
Answer: D. At k = 8, 64 > 50 sets found, then k++ still runs, so k is 9 when !found stops the loop.
Why the others are wrong:
- A is the largest
kwithk * kat most 50. - B is the value that passed the test, forgetting that
k++runs after it. - C ignores
!found, as if the loop ran untilkpassed 20.
- Exam-style This code segment should print the largest value of
k * k - 6 * kforkfrom 1 to 5. The values are all negative.
int max = /* initial value */;
for (int k = 1; k <= 5; k++)
{
int v = k * k - 6 * k;
if (v > max)
{
max = v;
}
}
System.out.println(max);
Which initial value makes it print the correct result?
- A)
Integer.MIN_VALUE - B)
0 - C)
Integer.MAX_VALUE - D)
-1
Show answer
Answer: A. Every value beats Integer.MIN_VALUE, so max ends at the true maximum, -5.
Why the others are wrong:
- B: no negative value beats 0, so it prints 0.
- C: no value beats the largest
int, so it prints 2147483647. - D: every value is below -1, so it prints -1.
- Recall Name the operator that, used with 10, gives the last digit of a positive int
n.
Show answer
Answer: The remainder operator, %, as in n % 10.
Marking points:
n / 10removes the last digit;n % 10gives it.
Key points
Recall, then reveal
Say the main points from memory first, then check them.
Show key pointsHide key points
- Set up before the loop, update inside, use after.
- Cast before dividing for an average:
(double) sum / count. - Start a max at
Integer.MIN_VALUEor the first value, a min atInteger.MAX_VALUEor the first value. n % 10is the last digit of a positive int,n / 10drops it.- "Any" flags start
false; "all" flags starttrue; neither is reset in the loop.