Loop patterns, sums and star patterns
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:
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");
}
}Iteration number 1
Iteration number 2
Iteration number 3
Loop finishedTracing a loop means writing down what happens, step by step:
| Step | i | Is i <= 3? | What runs |
|---|---|---|---|
| 1 | 1 | yes | prints "Iteration number 1", then i++ |
| 2 | 2 | yes | prints "Iteration number 2", then i++ |
| 3 | 3 | yes | prints "Iteration number 3", then i++ |
| 4 | 4 | no | the 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:
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
}
}Sum of 1 to 10 = 55| i | sum before | sum after |
|---|---|---|
| 1 | 0 | 1 |
| 2 | 1 | 3 |
| 3 | 3 | 6 |
| ... | ... | ... |
| 10 | 45 | 55 |
Counting down: 10 to 1 in reverse
Start high, keep going while i >= 1, and subtract with i--:
public class Main {
public static void main(String[] args) {
for (int i = 10; i >= 1; i--) {
System.out.print(i + " ");
}
System.out.println();
}
}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:
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);
}
}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 = 55Sums with a condition, and counting
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");
}
}Even sum: 30, odd sum: 25
14 numbers from 1 to 100 divide by 7Factorial and times tables
A product starts at 1, not 0. Factorials grow fast, so use long:
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));
}
}
}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 = 70Totals over an array
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);
}
}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:
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);
}
}Digit sum: 19
Reversed: 6904Patterns 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:
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();
}
}
}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:
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();
}
}
} *
***
*****
*******
*********
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:
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);
}
}Add up 1 to which number?
1 + 2 + ... + 100 = 5050
Formula check: 5050