Skip to lesson

Tracing a loop: totals and counts

Tracing a loop means following it one round at a time and writing down every variable after each step. With a trace you can predict what a loop prints, and build totals, counts and products with confidence.

Tracing round by round

What does the program below print? Guessing is risky: one wrong round changes the answer.

Follow it the way Java does and keep a trace table: one row per step, with the value of i, whether the condition is true, and every variable that changes. Step through it, then try the same on paper for i <= 5 (the answer is 15).

Trace the code

Fill the trace table

public class SumToFour {
public static void main(String[] args) {
int sum = 0;
for (int i = 1; i <= 4; i++) {
sum = sum + i;
}
System.out.println("Sum: " + sum);
}
}

Variables

sum
0

Output

(nothing printed yet)

Line 3sum is made before the loop and starts at 0.

Step 1 of 11

Running total

You want the total of 5 marks, adding one mark per round. Keep it in an accumulator: a variable made before the loop and started at 0, that each round adds to with total += mark.

A running total: total starts at 0, then adds 85, 78, 92, 66 and 74 in five rounds, becoming 85, 163, 255, 321 and finally 395 after the loop.

Example 1 · Total and average of 5 marks

MarksTotal.javaJava
import java.util.Scanner;
public class MarksTotal {    public static void main(String[] args) {        Scanner sc = new Scanner(System.in);        int total = 0;        for (int i = 1; i <= 5; i++) {            System.out.print("Enter mark " + i + ": ");            int mark = sc.nextInt();            total += mark;        }        System.out.println("Total: " + total);        System.out.println("Average: " + total / 5.0);        sc.close();    }}
Sample output
Enter mark 1: 85
Enter mark 2: 78
Enter mark 3: 92
Enter mark 4: 66
Enter mark 5: 74
Total: 395
Average: 79.0

What this code does

  • total is declared before the loop, so it keeps its value from round to round and still exists after the loop.
  • Each round reads one mark and adds it: 0, 85, 163, 255, 321, 395, as in the picture.
  • total / 5.0 divides by a double, so the average keeps its decimal part.
If you declare total inside the loop, it is made again with 0 every round, and it does not exist after the loop. Declare it before the loop.

Counting with a counter

How many numbers from 1 to 50 does 7 divide exactly? Keep a count variable that starts at 0, and add 1 to it only in the rounds where an if (opens in a new tab) check passes.

Example 2 · Counting multiples of 7

CountSevens.javaJava
public class CountSevens {    public static void main(String[] args) {        int count = 0;        for (int i = 1; i <= 50; i++) {            if (i % 7 == 0) {                count++;            }        }        System.out.println("Multiples of 7 up to 50: " + count);    }}
Output
Multiples of 7 up to 50: 7

What this code does

  • i % 7 == 0 is true for 7, 14, 21, 28, 35, 42 and 49, so count++ runs 7 times.
  • The loop runs 50 rounds, but the count grows only when the check passes.

Multiplying in a loop

5 factorial, written 5!, is 1 x 2 x 3 x 4 x 5 = 120. A product variable starts at 1, because multiplying by 1 changes nothing, and each round multiplies it by the counter: fact *= i.

Example 3 · 5 factorial

Factorial.javaJava
public class Factorial {    public static void main(String[] args) {        long fact = 1;        for (int i = 1; i <= 5; i++) {            fact *= i;        }        System.out.println("5! = " + fact);    }}
Output
5! = 120

What this code does

  • Trace: 1 x 1 = 1, 1 x 2 = 2, 2 x 3 = 6, 6 x 4 = 24, 24 x 5 = 120.
  • fact starts at 1, not 0; with 0 every product would be 0.

Products grow very fast: 13! is already too big for an int, so fact is a long (int and long (opens in a new tab)).

Next step

Check your understanding

8 quick questions