Questions or a demo for your school?Student? Sit a test
BrainBit Infotech TeachingStart free

Core Java notes · Topic 5 of 20 · 6 min read

Java loops: for, while and do-while

Java loops notes with examples: for, while and do-while loops, break and continue, labelled break, nested loops, number programs and star patterns.

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
}
  1. The initialisation runs once: int i = 1.
  2. The condition is checked; if it is false the loop ends.
  3. The body runs.
  4. 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?

LoopChecks conditionUse when
forbefore each turnyou know the count (1 to 10, every array index)
whilebefore each turnyou repeat until something happens
do-whileafter each turnthe body must run at least once (menus, input checks)

break and continue

  • break stops the loop immediately.
  • continue skips 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 <= 10 versus i < 10 changes the count by one.
  • Forgetting to update the variable in a while loop, so it never ends.
  • Using int for a large factorial: 13! does not fit in an int; use long.
  • Using the loop variable after a for loop that declared it; it no longer exists.

Key points

  • for suits a known count; while repeats until a condition fails; do-while always runs once.
  • break leaves the loop, continue skips to the next turn, and a label lets break leave an outer loop.
  • In nested loops the inner loop finishes fully for each outer turn.
  • % 10 gives the last digit and / 10 removes 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);   // 18
4. 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();
}