Informal run-time analysis means counting how many times a statement runs for a stated input size, then seeing how that count grows as the input grows. A loop over n values runs about n times, full nested loops run n × n times, and a halving loop runs only a few times. Comparing counts shows which of two segments doing the same job does less work.
Quick check
How many times does the body of for (int k = 0; k < 7; k++) run?Show answerHide answer
7 times, for
k= 0 to 6.An outer loop runs 5 times and a fixed inner loop runs 5 times on each pass. How many times does the inner body run?Show answerHide answer
25 times: 5 × 5. The note on nested loops shows why the counts multiply.
If n doubles, what happens to n × n?Show answerHide answer
It becomes 4 times as large, because (2n) × (2n) = 4n².
Know these already? Jump to the practice questions
What you'll be able to do
- Calculate how many times a statement in a single loop runs for a given input.
- Calculate the count for a statement inside nested loops, including dependent bounds.
- Compare two code segments that do the same job by their statement counts.
- Explain how a count grows when the input size doubles.
Key terms
Statement execution count
The number of times a particular statement runs when the code runs on a given input.
- In plain English
- How many times that line actually happens.
- Don't write
- "The count is the number of lines in the code."
Input size
The quantity that controls how much work the code does, such as n in a loop bound or the length of a string.
- In plain English
- How big the job is.
- Don't write
- "The input size is the value the method returns."
How do you count runs of a statement in a single loop?
List the values the loop variable takes; the body runs once for each. For for (int k = a; k < b; k++) that is b - a runs. If the update is k += 3, list the values instead of dividing in your head.
int count = 0;
for (int k = 0; k < 10; k += 3)
{
count++;
}
k takes 0, 3, 6 and 9, so count++ runs 4 times. At k = 12 the condition fails.
The condition is checked once more than the body runs, because the last check is the one that comes out false. Here k < 10 is checked 5 times. A question can ask about either count, so read which statement it names. Loop syntax is not on the Java Quick Reference: Learn this.
Check yourself
Show answerHide answer
6 times: true for 0 to 4, then false at 5.
How do you count a statement inside nested loops?
Use the method from the note on nested loops. With fixed bounds, multiply: two loops of n passes run the inner body n × n times. When the inner bound uses the outer variable, add the inner counts: with j from i + 1 to n - 1, the counts are n - 1, n - 2, …, 0, which add to n(n − 1) / 2.
For n = 8 that gives 64 runs for full nested loops and 28 for the dependent version. A fixed inner count of 3 gives only 3 × 8 = 24, because only the outer loop depends on n.
Check yourself
Show answerHide answer
190, from 20 × 19 / 2.
How do you compare two segments that do the same job?
Count the same kind of step in each, for the same input, and compare. Both segments below set sum to 1 + 2 + … + n, where n is a positive int up to 1000.
// Segment I
int sum = 0;
for (int k = 1; k <= n; k++)
{
sum += k;
}
// Segment II
int sum = n * (n + 1) / 2;
For n = 100, Segment I runs sum += k 100 times, while Segment II runs its one assignment once. Both give 5050. Segment I's count grows with n; Segment II's stays at 1 whatever n is, so Segment II does less work.
Key idea
Compare segments by counting a statement for the same input, not by how long the code looks.
Check yourself
Show answerHide answer
Segment I runs sum += k 1000 times; Segment II runs its assignment once.
How does the count grow as the input grows?
Work out each count for a few sizes and watch what doubling does.
n | Single loop | Full nested loops | Halving loop |
|---|---|---|---|
| 8 | 8 | 64 | 3 |
| 16 | 16 | 256 | 4 |
| 32 | 32 | 1024 | 5 |
The halving loop is while (k > 1) { k = k / 2; } with k starting at n. When n doubles, a single loop's count doubles (linear growth), a full nested loop's count multiplies by 4 (quadratic growth), and the halving loop's count goes up by only 1.
Check yourself
Show answerHide answer
600 times: the count doubles when n doubles.
Worked example 1: Count a loop that steps by 3
Question: How many times does total += k; run?
int n = 20;
int total = 0;
for (int k = 1; k < n; k += 3)
{
total += k;
}
What tells you the method
A single loop with a step other than 1: list the values of k.
Step 1: List the values of
kthat pass the condition.Pass 1 2 3 4 5 6 7 k1 4 7 10 13 16 19 Whykstarts at 1 and goes up by 3; the next value, 22, failsk < 20.Step 2: Count the passes.
There are 7 values, so the statement runs 7 times.
WhyThe body runs once for each value that passes the condition.
Check it
The last value, 19, is below 20, and 19 + 3 = 22 is not, so 19 really is the last pass.
Answer
7
Worked example 2: Watch a triangular count grow
Question: How many stars are printed (a) when n is 6 and (b) when n is 12?
for (int i = 0; i < n; i++)
{
for (int j = 0; j < i; j++)
{
System.out.print("*");
}
}
What tells you the method
The inner bound uses i, so add the inner counts, then compare the two sizes.
Step 1: Add the inner counts for
n= 6.For
i= 0 to 5 the inner loop runs 0, 1, 2, 3, 4, 5 times, which adds to 15.Whyjruns from 0 up toi - 1, so the inner loop runsitimes.Step 2: Use the pattern for
n= 12.The sum is 0 + 1 + … + 11, which is 12 × 11 / 2 = 66.
WhyAdding 0 to n − 1 gives n(n − 1) / 2.
Step 3: Compare.
66 is 4.4 times 15: doubling
nroughly quadruples the count.Whyn(n − 1) / 2 grows like n², so the growth is quadratic.
Check it
For n = 6, 6 × 5 / 2 = 15, which matches the sum in Step 1.
Answer
(a) 15 (b) 66
Worked example 3: Compare two segments
Question: Both segments set count (which starts at 0) to the number of pairs with i < j, where i and j run from 0 to n - 1. When n is 50, how many times is i < j tested in Segment I, and how many times does count++ run in Segment II?
// Segment I
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
if (i < j)
{
count++;
}
}
}
// Segment II
for (int i = 0; i < n; i++)
{
for (int j = i + 1; j < n; j++)
{
count++;
}
}
- A) 2,500 and 1,225
- B) 2,500 and 2,500
- C) 1,225 and 1,225
- D) 2,500 and 1,275
What tells you the method
Two segments, one input: count each named statement separately.
Step 1: Count Segment I's tests.
Both loops run 50 times with fixed bounds, so
i < jis tested 50 × 50 = 2,500 times.WhyThe
ifsits in the inner body, so it runs on every inner pass, whether or not it is true.Step 2: Count Segment II's runs.
jstarts ati + 1, so the inner counts are 49, 48, …, 0, which add to 50 × 49 / 2 = 1,225.WhyDependent bounds mean you add, not multiply.
Check it
Segment I's test is true exactly 1,225 times, the same count Segment II reaches, which confirms the two segments do the same job.
Answer
A
Your turn
Question: How many times does steps++; run?
int k = 64;
int steps = 0;
while (k > 1)
{
k = k / 2;
steps++;
}
Step 1: First pass.
64 > 1, so
kbecomes 32 andstepsis 1.Step 2: Second pass.
32 > 1, so
kbecomes 16 andstepsis 2.Step 3: Your go: keep halving until
k > 1is false, and count the passes.
Show the full solutionHide the solution
Step 3. k goes 8, 4, 2, 1 on passes 3 to 6. When k is 1, k > 1 is false, so the loop stops after 6 passes. Starting at 128 would add just one more pass.
Answer: 6
Traps
Trap
A loop's condition is checked exactly as many times as its body runs.
It seems right because each pass begins with a check. But the loop also needs one final check that comes out false, so the condition is checked one more time than the body runs.
In for (int k = 0; k < 4; k++), how many times does the body run, and how many times is k < 4 checked?
The body runs 4 times and k < 4 is checked 5 times.
Trap
Any two nested loops run the inner statement n × n times.
It seems right because each loop mentions n somewhere. But a dependent inner bound gives about half that, and an inner loop with a fixed count of 3 gives just 3n.
For n = 10, how many times does the inner body run when the inner loop is for (int j = 0; j < 3; j++)?
30 times: 10 outer passes × 3 inner passes.
What's examined
On the AP® Computer Science A exam (Unit 2: Selection and Iteration), multiple-choice questions ask what code segments print or which code completes them, and counting how many times a statement runs helps you trace and compare them. Name the statement you are counting, and check the first and last pass.
Practice questions
- Recall A statement sits inside two nested loops that each run
ntimes with fixed bounds. Ifndoubles, how does the number of times it runs change?
- A) It doubles.
- B) It stays the same.
- C) It becomes 4 times as large.
- D) It goes up by 1.
Show answer
Answer: C. The count is n × n, and (2n) × (2n) = 4n²: 100 runs at n = 10 become 400 at n = 20.
Why the others are wrong:
- A is the growth of a single loop.
- B ignores that both bounds depend on
n. - D is the growth of a halving loop.
- Apply How many times does the body of
for (int k = 0; k < 30; k += 4)run?
Show answer
Answer: 8
Marking points:
ktakes 0, 4, 8, 12, 16, 20, 24, 28; the next value, 32, failsk < 30.
- Apply How many times is the condition
k <= 10checked whenfor (int k = 1; k <= 10; k++)runs?
Show answer
Answer: 11
Marking points:
- It is true for
k= 1 to 10 (10 checks) and false once at 11.
- Exam-style What value does
sumhold after this code segment runs?
int n = 10;
int sum = 0;
for (int i = 1; i <= n; i++)
{
for (int j = 1; j <= n; j += 2)
{
sum++;
}
}
Show answer
Answer: 50
Marking points:
- The inner loop runs for
j= 1, 3, 5, 7, 9: 5 passes. - The bounds are fixed, so 10 × 5 = 50.
- Exam-style For
n= 1000, which loop runs its body the fewest times?
- A)
for (int k = 0; k < n; k++) - B)
for (int k = 1; k < n; k *= 2) - C)
for (int k = 0; k < n; k += 2) - D)
for (int k = n; k > 0; k -= 10)
Show answer
Answer: B. k doubles: 1, 2, 4, …, 512, which is 10 passes.
Why the others are wrong:
- A runs 1000 times.
- C runs 500 times: a bigger step still grows in proportion to
n. - D runs 100 times, for the same reason.
- Exam-style For any
nfrom 1 to 1,000,000, both segments setprimetotrueexactly whennis a prime number. Whennis 97, a prime, how many times does each segment run the testn % d == 0?
// Segment I
boolean prime = n > 1;
for (int d = 2; d < n; d++)
{
if (n % d == 0) { prime = false; }
}
// Segment II
boolean prime = n > 1;
for (int d = 2; d * d <= n; d++)
{
if (n % d == 0) { prime = false; }
}
- A) 96 and 9
- B) 95 and 47
- C) 95 and 95
- D) 95 and 8
Show answer
Answer: D. Segment I tests d = 2 to 96 (95 values). Segment II stops when d * d passes 97: 9 × 9 = 81 is allowed but 10 × 10 = 100 is not, so it tests d = 2 to 9 (8 values).
Why the others are wrong:
- A counts the loop conditions, which are checked one extra time each.
- B stops Segment II at
n / 2instead of whered * dexceedsn. - C ignores the
d * d <= nbound and tests every value in both.
- Recall A segment's statement count doubles every time
ndoubles. Does the count grow linearly or quadratically?
Show answer
Answer: Linearly. A count that doubles when n doubles grows in proportion to n.
Marking points:
- Quadratic growth would multiply the count by 4 when
ndoubles.
Key points
Recall, then reveal
Say the main points from memory first, then check them.
Show key pointsHide key points
- List the loop variable's values: the body runs once per value that passes the condition.
- The condition is checked one more time than the body runs.
- Fixed nested bounds multiply; dependent bounds add, often to n(n − 1) / 2.
- When
ndoubles: single loop ×2, full nested loops ×4, halving loop +1. - To compare segments that do the same job, count a named statement for the same input.