Why loops?
A loop repeats a block of code. Printing the 7 times table needs ten lines without a loop and three with one:
for (int i = 1; i <= 10; i++) {
System.out.println("7 x " + i + " = " + 7 * i);
}
Java has three loops: for, while and do-while, plus the for-each loop for arrays and collections (covered in the Arrays topic).
The for loop
for (initialisation; condition; update) {
// body
}
- The initialisation runs once:
int i = 1. - The condition is checked; if it is false the loop ends.
- The body runs.
- The update runs (
i++) and Java goes back to step 2.
int sum = 0;
for (int i = 1; i <= 100; i++) {
sum += i;
}
System.out.println(sum); // 5050
Counting down and stepping:
for (int i = 10; i >= 1; i--) { System.out.print(i + " "); } // 10 9 ... 1
for (int i = 0; i <= 20; i += 5) { System.out.print(i + " "); } // 0 5 10 15 20
A variable declared in the for header (int i) exists only inside the loop.
The while loop
Use while when you do not know in advance how many times to repeat:
int n = 4729;
int digits = 0;
while (n > 0) {
n /= 10;
digits++;
}
System.out.println(digits); // 4
The condition is checked before each turn, so the body may run zero times.
The do-while loop
The body runs first and the condition is checked after, so it always runs at least once. It suits menus and "ask again" input:
import java.util.Scanner;
Scanner sc = new Scanner(System.in);
int pin;
do {
System.out.print("Enter 4-digit PIN: ");
pin = sc.nextInt();
} while (pin < 1000 || pin > 9999);
Note the semicolon after while (...) in a do-while.
Which loop when?
| Loop | Checks condition | Use when |
|---|---|---|
for | before each turn | you know the count (1 to 10, every array index) |
while | before each turn | you repeat until something happens |
do-while | after each turn | the body must run at least once (menus, input checks) |
break and continue
breakstops the loop immediately.continueskips the rest of this turn and moves to the next one.
for (int i = 1; i <= 10; i++) {
if (i == 6) break;
System.out.print(i + " "); // 1 2 3 4 5
}
for (int i = 1; i <= 10; i++) {
if (i % 3 == 0) continue;
System.out.print(i + " "); // 1 2 4 5 7 8 10
}
Labelled break
In nested loops, a plain break leaves only the inner loop. A label leaves the outer one too:
outer:
for (int r = 1; r <= 3; r++) {
for (int c = 1; c <= 3; c++) {
if (r * c == 4) {
System.out.println("Found at " + r + "," + c);
break outer;
}
}
}
Nested loops and patterns
The inner loop runs completely for each turn of the outer loop.
public class Pyramid {
public static void main(String[] args) {
int n = 4;
for (int i = 1; i <= n; i++) {
for (int s = 1; s <= n - i; s++) System.out.print(" ");
for (int k = 1; k <= 2 * i - 1; k++) System.out.print("*");
System.out.println();
}
}
}
*
***
*****
*******
Classic number programs
Reverse a number and check a palindrome
int n = 1221, original = n, rev = 0;
while (n > 0) {
rev = rev * 10 + n % 10;
n /= 10;
}
System.out.println(original == rev ? "Palindrome" : "Not a palindrome");
Prime check
int n = 29;
boolean prime = n > 1;
for (int i = 2; i * i <= n; i++) {
if (n % i == 0) { prime = false; break; }
}
System.out.println(n + (prime ? " is prime" : " is not prime"));
Checking up to the square root (i * i <= n) is enough: if n has a factor larger than its square root, it also has one smaller.
Factorial
int n = 5;
long fact = 1;
for (int i = 2; i <= n; i++) fact *= i;
System.out.println(fact); // 120
Common mistakes
- A semicolon after the header:
for (int i = 0; i < 5; i++);runs an empty body five times. - Off-by-one errors:
i <= 10versusi < 10changes the count by one. - Forgetting to update the variable in a
whileloop, so it never ends. - Using
intfor a large factorial: 13! does not fit in anint; uselong. - Using the loop variable after a
forloop that declared it; it no longer exists.
Key points
forsuits a known count;whilerepeats until a condition fails;do-whilealways runs once.breakleaves the loop,continueskips to the next turn, and a label letsbreakleave an outer loop.- In nested loops the inner loop finishes fully for each outer turn.
% 10gives the last digit and/ 10removes it: the basis of most digit programs.
Practice questions
1. How many times does the body run? for (int i = 3; i < 20; i += 4)
5 times: i is 3, 7, 11, 15 and 19.
2. What is the main difference between while and do-while?
while checks the condition first, so its body may never run. do-while checks after the body, so the body runs at least once.
3. Print the sum of the digits of 5823.
int n = 5823, sum = 0;
while (n > 0) {
sum += n % 10;
n /= 10;
}
System.out.println(sum); // 184. Print the first 10 Fibonacci numbers: 0 1 1 2 3 5 8 13 21 34.
int a = 0, b = 1;
for (int i = 1; i <= 10; i++) {
System.out.print(a + " ");
int next = a + b;
a = b;
b = next;
}5. Print a right-angled triangle of numbers with 4 rows: 1 / 1 2 / 1 2 3 / 1 2 3 4.
for (int i = 1; i <= 4; i++) {
for (int j = 1; j <= i; j++) System.out.print(j + " ");
System.out.println();
}