Informal Run-Time Analysis
Measuring how much work code does by counting how many times its statements execute: counts for single, stepped, halving, and nested loops, how counts grow with input size, and how to compare two correct algorithms.
Two programs can produce the same answer while doing very different amounts of work. A statement execution count indicates the number of times a statement is executed by the program. Statement execution counts are often calculated informally through tracing and analysis of the iterative statements, and they make it possible to predict how running time changes as the input grows and to compare algorithms. A single loop's count grows in step with its input; a nested loop's count grows much faster; a halving loop's count barely grows at all.
1Statement Execution Counts
Statements outside any loop execute once. Statements inside a loop execute once per pass, and statements inside nested loops execute once per pass of the innermost loop. Counting how many times a particular statement runs, usually the one in the innermost body, gives a simple measure of how much work a code segment does, independent of how fast a particular computer is.
Timing a program with a clock is less useful for this purpose, because the same code runs at different speeds on different machines and even from one run to the next. Counts are exact and repeatable, and they can be worked out by reading the code, before it ever runs. That makes them the right tool for comparing designs while a program is still being written.
For a for loop, each part of the header has its own count. The initialization runs once; the Boolean expression runs once per pass plus one final time when it fails; the body and the update run once per pass. Questions usually ask about one specific statement, so identify it first and then count how many passes reach it.
Part of for (int i = 0; i < n; i++) | Executions |
|---|---|
| Initialization | 1 |
| Boolean expression | n + 1 |
| Body statement | n |
| Update | n |
Let the Program Count for You
Add a counter to measure how many times the body runs, then compare with the prediction n.
int n = 7;
int sum = 0;
int bodyCount = 0;
for (int i = 0; i < n; i++)
{
sum += i;
bodyCount++;
}
System.out.println(sum + " " + bodyCount);
21 7
- 1Prediction.
itakes the values 0 to 6, so the body runsn= 7 times. - 2Measurement. The extra counter confirms 7.
- 3Other parts. The check
i < nruns 8 times and the update 7 times; the initialization runs once.
A loop whose body runs n times evaluates its Boolean expression n + 1 times: once before each pass and once more when it becomes false. If a question asks how many times the condition is evaluated, include that last check.
2Counting Single Loops
For a loop whose control variable goes from a to b inclusive in steps of 1, the body runs b - a + 1 times; with a strict < bound it runs b - a times. For larger steps, the count is roughly the length of the range divided by the step, but off by one surprises are common, so listing the values that pass the check is safer than dividing.
Statements inside an if within a loop run only on the passes where the condition is true. Their counts depend on the data, not just the loop bounds: counting the multiples of 7 from 1 to 100 runs the loop body 100 times but the counter update only 14 times.
Counting a Loop That Skips
How many times does the body run?
int count = 0;
for (int i = 0; i < 20; i += 3)
{
count++;
}
System.out.println(count);
7
- 1List the values. 0, 3, 6, 9, 12, 15, 18 pass the check; 21 fails.
- 2Count them: 7.
for (int i = 0; i < 20; i += 3) runs 7 times, not 20 / 3 ≈ 6.7 or 6. Whether the endpoints count depends on the starting value and the bound. List the values that pass the check whenever the step is not 1.
3Counting Nested Loops
For nested loops whose inner bound does not depend on the outer variable, the inner body runs (outer passes) × (inner passes) times: two loops of n passes each give n² executions. When the inner bound depends on the outer variable, add the inner counts for each outer pass; for inner counts 0, 1, …, n − 1, the total is n(n − 1) / 2.
These two results are the most common nested-loop counts. Both grow roughly with the square of n: the triangle does about half the work of the square, but doubling n still roughly quadruples either one. That rapid growth is why nested loops over large inputs can be slow.
Fixed and Dependent Inner Loops
For n = 5, predict how many times each inner statement runs.
int n = 5;
int fixedCount = 0;
int triangleCount = 0;
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
fixedCount++;
}
for (int j = 0; j < i; j++)
{
triangleCount++;
}
}
System.out.println(fixedCount + " " + triangleCount);
25 10
- 1Fixed inner bound. 5 × 5 = 25.
- 2Bound
j < i. 0 + 1 + 2 + 3 + 4 = 10, which isn(n − 1) / 2. - 3Comparison. The triangle does a little under half the work of the square for the same
n.
A Triangle Counted Without Running It
How many times does the println run? Work it out before running the code.
int lines = 0;
for (int i = 1; i <= 4; i++)
{
for (int j = i; j <= 4; j++)
{
System.out.println(i + "-" + j);
lines++;
}
}
System.out.println(lines + " lines");
1-1
1-2
1-3
1-4
2-2
2-3
2-4
3-3
3-4
4-4
10 lines
- 1Inner counts. For
i= 1,jruns 1 to 4: 4 times. Fori= 2: 3 times. For 3: 2. For 4: 1. - 2Add them: 4 + 3 + 2 + 1 = 10.
println inside runs 10 times, matching the count computed by hand. Tracing the inner count for each outer value and adding gives statement counts without running anything.4Counting Halving Loops
A loop that divides its control variable by 2 each pass, as in while (n > 1) { n = n / 2; }, needs only as many passes as it takes to halve n down to 1. Starting from 1000 that is 9 passes; from 2000, 10; from a million, about 20. Doubling the starting value adds just one pass.
This slow growth is why repeatedly cutting a problem in half is such a powerful idea in computing. A process that eliminates half of the remaining possibilities each step, such as guessing a number between 1 and 1000 with "higher" or "lower" hints, finishes in a handful of steps even for very large ranges.
How Many Halvings From 1000?
Count the passes for starting values 1000 and 2000.
public static int halvings(int n)
{
int passes = 0;
while (n > 1)
{
n = n / 2;
passes++;
}
return passes;
}
9
10
19
- 11000: 500, 250, 125, 62, 31, 15, 7, 3, 1: 9 passes.
- 22000: one extra halving reaches 1000, so 10.
- 31,000,000: only 19 passes.
5How Counts Grow
Informal analysis is most useful for predicting what happens as inputs get larger. Compare the counts for a few sizes, such as n = 10, 20, 40, 80. A single loop's count doubles each time n doubles. A nested loop's count quadruples. A halving loop's count increases by one. These patterns hold no matter how fast the computer is.
For small inputs, any reasonable algorithm is fast enough. The differences matter when inputs grow to thousands or millions of values: a single loop over a million values does a million steps, while a nested loop over them would do a trillion. Recognizing the shape of the loops in a program, and therefore how its count grows, is the core of informal run-time analysis.
| Loop shape | Inner statement count | Example |
|---|---|---|
| Single loop, step 1, n values | n | for (i = 0; i < n; i++) |
| Single loop, step k | about n / k | for (i = 0; i < 20; i += 3): 7 |
| Halving loop | number of halvings (small) | 1000 → 1: 9 passes |
| Nested, fixed bounds | n × m | 5 × 5 = 25 |
| Nested, inner bound depends on outer | sum of inner counts | 0 + 1 + 2 + 3 + 4 = 10 |
| n | Single loop (n) | Nested (n × n) | Halving from n |
|---|---|---|---|
| 10 | 10 | 100 | 3 |
| 20 | 20 | 400 | 4 |
| 40 | 40 | 1,600 | 5 |
| 80 | 80 | 6,400 | 6 |
Two algorithms may take about the same time for n = 5 and wildly different times for n = 5,000. Compare how their counts grow as n doubles, not just a single count at one small size.
6Comparing Algorithms
When two algorithms solve the same problem correctly, statement execution counts show which does less work. Counting divisors by testing every value from 1 to n takes n passes; testing only up to n / 2 and counting n itself separately takes about half as many, with the same result. Small insights about the problem often translate directly into fewer passes.
Efficiency never excuses an incorrect result, so check correctness first: the faster version must produce exactly the same answers, including at edge cases such as n = 1. Then compare counts, either by reasoning about the loops or by adding counters to both versions and running them on the same inputs.
Two Ways to Count Divisors
Both methods count the divisors of 100. Compare their answers and their loop passes.
public static void versionA(int n)
{
int divisors = 0;
int passes = 0;
for (int d = 1; d <= n; d++)
{
passes++;
if (n % d == 0)
{
divisors++;
}
}
System.out.println("A: " + divisors + " divisors, " + passes + " passes");
}
public static void versionB(int n)
{
int divisors = 1;
int passes = 0;
for (int d = 1; d <= n / 2; d++)
{
passes++;
if (n % d == 0)
{
divisors++;
}
}
System.out.println("B: " + divisors + " divisors, " + passes + " passes");
}
A: 9 divisors, 100 passes
B: 9 divisors, 50 passes
- 1Version A tests every candidate from 1 to
n: 100 passes. - 2Version B starts its count at 1 for
nitself and tests only up ton / 2, because no other divisor can be larger: 50 passes. - 3Same answer. Both find 9 divisors; B does half the work.
Adding 1 Through n Two Ways
Both approaches compute 1 + 2 + … + 100. Compare the number of additions each performs.
int n = 100;
int total = 0;
int additions = 0;
for (int k = 1; k <= n; k++)
{
total += k;
additions++;
}
int formula = n * (n + 1) / 2;
System.out.println(total + " after " + additions + " additions");
System.out.println(formula + " from one calculation");
5050 after 100 additions
5050 from one calculation
- 1The loop performs one addition per value:
n= 100 of them. - 2The formula
n(n + 1) / 2uses a fixed handful of operations whatevernis. - 3Growth. For
n= 1,000,000, the loop would do a million additions; the formula still does a few operations.
A version that does half the work but gives the wrong answer for some inputs is not an improvement. In the divisor example, check n = 1: n / 2 is 0, so the loop makes no passes, and the count that started at 1 for n itself correctly reports one divisor. A faster version that forgot to count n itself would report too few for every input. Always confirm the edge cases.
Four Habits for Counting Work
1. Pick the Statement
Count the innermost statement the question names.
2. List When Unsure
Write the values that pass the check, then count them.
3. Multiply or Add
Fixed nested bounds multiply; dependent bounds add.
4. Watch the Growth
Double n: single ×2, nested ×4, halving +1.
A statement execution count indicates the number of times a statement is executed by the program. Statement execution counts are often calculated informally through tracing and analysis of the iterative statements. A loop body with n passes contributes n executions and its Boolean expression n + 1; nested loops multiply their pass counts when the bounds are fixed and add the inner counts when the inner bound depends on the outer variable; a loop that halves its variable needs only a few passes. Comparing counts, and how they grow as the input grows, allows algorithms to be compared informally.