AI Hints
Home›Java Tutorial›Counting and Summing, Infinite Loops and Off-by-One, Practice: Times Table
Java · Lesson 43 of 120

Counting and Summing

Running totals.

⏱ 2 min read▶ Video at 54:22🎓 Free
Watch this lesson in the Java courseWatch on YouTube ↗Full Java course

Adding things up is one of the most common jobs for a loop. You keep a running total, and add to it on every lap.

  • Add things up
  • A running total
  • Updated every lap

Totals and counts

Total starts at zero. Each lap adds the next number. After a hundred laps, total holds the sum of one to a hundred. Counting works the same way, but adds one at a time. Run it. The sum is five thousand and fifty. And there are fifty even numbers.

Main.javajava
public class Main {
    public static void main(String[] args) {
        int total = 0;
        for (int i = 1; i <= 100; i++) {
            total += i;
        }
        System.out.println("1 + 2 + ... + 100 = " + total);

        int evens = 0;
        for (int i = 1; i <= 100; i++) {
            if (i % 2 == 0) evens++;
        }
        System.out.println("Even numbers: " + evens);
    }
}
Output
1 + 2 + ... + 100 = 5050
Even numbers: 50

An average from input

Now the numbers come from the keyboard. We keep a sum, and a count. The loop keeps reading prices, until the user types zero. The average is the sum, divided by the count. Run it. Four prices, adding up to twelve pounds. The average is three pounds.

Main.javajava
import java.util.Scanner;
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int count = 0;
        double sum = 0;
        System.out.println("Enter prices, 0 to finish:");
        double price = in.nextDouble();
        while (price != 0) {
            sum += price;
            count++;
            price = in.nextDouble();
        }
        System.out.printf("%d items, total %.2f, average %.2f%n", count, sum, sum / count);
    }
}
Input typed: 2.50 · 4.00 · 1.75 · 3.75 · 0
Output
Enter prices, 0 to finish:
2.50
4.00
1.75
3.75
0
4 items, total 12.00, average 3.00

Summary

Start a total at zero, and add to it in the loop. Divide by the count to get an average. Next, two classic loop mistakes.

Key takeaways
  • total = 0
  • total += value
  • average = sum / count
Next up: Infinite Loops and Off-by-One — classic loop mistakes