CodeMIRAI
0 XP

Loop patterns, sums and star patterns

5 min read 11 runnable examples Quiz included

A loop on its own just repeats. Most real loops build up an answer one step at a time: a total, a count, a product. This lesson collects the patterns you'll meet in class and in exams. The output of each example is shown under it.

Iteration: one trip round the loop

Each pass through a loop's body is called an iteration:

Java
public class Main {
    public static void main(String[] args) {
        for (int i = 1; i <= 3; i++) {
            System.out.println("Iteration number " + i);
        }
        System.out.println("Loop finished");
    }
}
Output
Iteration number 1
Iteration number 2
Iteration number 3
Loop finished

Tracing a loop means writing down what happens, step by step:

StepiIs i <= 3?What runs
11yesprints "Iteration number 1", then i++
22yesprints "Iteration number 2", then i++
33yesprints "Iteration number 3", then i++
44nothe loop stops

Adding up: the sum of 1 to 10

A variable that holds the running total is called an accumulator. Start it at 0 before the loop, add to it inside, and use it after:

Java
public class Main {
    public static void main(String[] args) {
        int sum = 0;                       // 1. start the total at 0
        for (int i = 1; i <= 10; i++) {
            sum = sum + i;                 // 2. add this number (also written sum += i)
        }
        System.out.println("Sum of 1 to 10 = " + sum);   // 3. use it after the loop
    }
}
Output
Sum of 1 to 10 = 55
isum beforesum after
101
213
336
.........
104555

Counting down: 10 to 1 in reverse

Start high, keep going while i >= 1, and subtract with i--:

Java
public class Main {
    public static void main(String[] args) {
        for (int i = 10; i >= 1; i--) {
            System.out.print(i + " ");
        }
        System.out.println();
    }
}
Output
10 9 8 7 6 5 4 3 2 1 

print stays on the same line; println ends the line.

The sum of 1 to 10, in reverse

The order of addition doesn't change the total, but the running totals differ:

Java
public class Main {
    public static void main(String[] args) {
        int sum = 0;
        for (int i = 10; i >= 1; i--) {
            sum += i;
            System.out.println("added " + i + ", total is " + sum);
        }
        System.out.println("Sum of 10 down to 1 = " + sum);
    }
}
Output
added 10, total is 10
added 9, total is 19
added 8, total is 27
added 7, total is 34
added 6, total is 40
added 5, total is 45
added 4, total is 49
added 3, total is 52
added 2, total is 54
added 1, total is 55
Sum of 10 down to 1 = 55

Sums with a condition, and counting

Java
public class Main {
    public static void main(String[] args) {
        int evens = 0, odds = 0, sevens = 0;
        for (int i = 1; i <= 10; i++) {
            if (i % 2 == 0) {
                evens += i;
            } else {
                odds += i;
            }
        }
        for (int i = 1; i <= 100; i++) {
            if (i % 7 == 0) {
                sevens++;                  // a counter adds 1 each time
            }
        }
        System.out.println("Even sum: " + evens + ", odd sum: " + odds);
        System.out.println(sevens + " numbers from 1 to 100 divide by 7");
    }
}
Output
Even sum: 30, odd sum: 25
14 numbers from 1 to 100 divide by 7

Factorial and times tables

A product starts at 1, not 0. Factorials grow fast, so use long:

Java
public class Main {
    public static void main(String[] args) {
        long fact = 1;
        for (int i = 1; i <= 10; i++) {
            fact *= i;
        }
        System.out.println("10! = " + fact);

        int n = 7;
        for (int i = 1; i <= 10; i++) {
            System.out.println(n + " x " + i + " = " + (n * i));
        }
    }
}
Output
10! = 3628800
7 x 1 = 7
7 x 2 = 14
7 x 3 = 21
7 x 4 = 28
7 x 5 = 35
7 x 6 = 42
7 x 7 = 49
7 x 8 = 56
7 x 9 = 63
7 x 10 = 70

Totals over an array

Java
public class Main {
    public static void main(String[] args) {
        int[] marks = {72, 85, 90, 64, 88};
        int total = 0;
        int highest = marks[0];
        for (int m : marks) {
            total += m;
            if (m > highest) {
                highest = m;
            }
        }
        System.out.println("Total: " + total);
        System.out.println("Average: " + (double) total / marks.length);
        System.out.println("Highest: " + highest);
    }
}
Output
Total: 399
Average: 79.8
Highest: 90

(double) total stops integer division from cutting off the decimals.

Digit sum and reversing a number

n % 10 is the last digit, and n / 10 (integer division) drops it:

Java
public class Main {
    public static void main(String[] args) {
        int n = 4096;
        int digitSum = 0, reversed = 0;
        while (n > 0) {
            int digit = n % 10;
            digitSum += digit;
            reversed = reversed * 10 + digit;
            n = n / 10;
        }
        System.out.println("Digit sum: " + digitSum);
        System.out.println("Reversed: " + reversed);
    }
}
Output
Digit sum: 19
Reversed: 6904

Patterns with nested loops

The outer loop picks the row; the inner loop prints that row's columns. The trick in every pattern is how the inner loop's limit depends on the row:

Java
public class Main {
    public static void main(String[] args) {
        int n = 5;
        System.out.println("Right triangle:");
        for (int row = 1; row <= n; row++) {
            for (int col = 1; col <= row; col++) {
                System.out.print("* ");
            }
            System.out.println();
        }
        System.out.println("Upside down:");
        for (int row = n; row >= 1; row--) {
            for (int col = 1; col <= row; col++) {
                System.out.print("* ");
            }
            System.out.println();
        }
        System.out.println("Numbers:");
        for (int row = 1; row <= n; row++) {
            for (int col = 1; col <= row; col++) {
                System.out.print(col + " ");
            }
            System.out.println();
        }
    }
}
Output
Right triangle:
* 
* * 
* * * 
* * * * 
* * * * * 
Upside down:
* * * * * 
* * * * 
* * * 
* * 
* 
Numbers:
1 
1 2 
1 2 3 
1 2 3 4 
1 2 3 4 5 

A pyramid needs spaces before the stars: row r has n - r spaces and 2r - 1 stars. Floyd's triangle keeps a counter outside both loops:

Java
public class Main {
    public static void main(String[] args) {
        int n = 5;
        for (int row = 1; row <= n; row++) {
            for (int s = 1; s <= n - row; s++) {
                System.out.print(" ");
            }
            for (int star = 1; star <= 2 * row - 1; star++) {
                System.out.print("*");
            }
            System.out.println();
        }
        int num = 1;
        for (int row = 1; row <= 4; row++) {
            for (int col = 1; col <= row; col++) {
                System.out.print(num + " ");
                num++;
            }
            System.out.println();
        }
    }
}
Output
    *
   ***
  *****
 *******
*********
1 
2 3 
4 5 6 
7 8 9 10 

Your turn: sum of 1 to n

This version reads n with a Scanner. The example's input is 100:

Java
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        System.out.print("Add up 1 to which number? ");
        int n = in.nextInt();
        int sum = 0;
        for (int i = 1; i <= n; i++) {
            sum += i;
        }
        System.out.println();
        System.out.println("1 + 2 + ... + " + n + " = " + sum);
        System.out.println("Formula check: " + n * (n + 1) / 2);
    }
}
Output
Add up 1 to which number? 
1 + 2 + ... + 100 = 5050
Formula check: 5050
Finished this lesson?Mark it complete to earn +20 XP and move your progress on.