TutorialsICSEClass 9Computer Applications

Loops in Java for ICSE Class 9: for, while, do-while and Nested Loops

ICSE Class 9 Computer Applications notes on loops in Java: for, while and do-while loops, entry vs exit control, break and continue, nested loops and pattern programs, with dry runs, output questions and solved programs.

13 min read
Loops in Java for ICSE Class 9: for, while, do-while and Nested Loops

Loops let a program repeat a set of statements without writing them again and again. Every number program, series and pattern in ICSE Computer Applications uses loops, and output questions on loops appear in almost every exam. These notes take you through all three loops, nested loops and the common exam traps.

Parts of a loop

Every loop has four parts:

  1. Initialisation: sets the starting value of the loop variable, for example int i = 1.
  2. Test condition: decides whether the loop body runs again, for example i <= 10.
  3. Body: the statements that are repeated.
  4. Update: changes the loop variable, for example i++.

The for loop

Use a for loop when you know how many times to repeat.

for (int i = 1; i <= 5; i++) {
    System.out.print(i + " ");
}
// Output: 1 2 3 4 5

Sum of the first n natural numbers:

int sum = 0;
for (int i = 1; i <= n; i++)
    sum += i;

The while loop

Use a while loop when the number of repetitions is not known in advance. A typical example is processing the digits of a number.

int n = 4721, sum = 0;
while (n > 0) {
    sum += n % 10;     // take the last digit
    n /= 10;           // remove the last digit
}
System.out.println(sum);   // 14

The do-while loop

The condition is checked after the body, so a do-while loop always runs at least once.

int i = 10;
do {
    System.out.println(i);
    i++;
} while (i < 5);
// Prints 10 once, even though the condition is false

Entry-controlled vs exit-controlled

  • Entry-controlled loops (for and while) check the condition before the body, so the body may run zero times.
  • Exit-controlled loops (do-while) check the condition after the body, so it always runs at least once.

break and continue

  • break ends the loop immediately.
  • continue skips the rest of the current iteration and moves on to the next one.
for (int i = 1; i <= 10; i++) {
    if (i % 3 == 0)
        continue;      // skip multiples of 3
    if (i > 7)
        break;         // stop after 7
    System.out.print(i + " ");
}
// Output: 1 2 4 5 7

Infinite and empty loops

  • Infinite loop: the condition never becomes false. For example, for (int i = 1; i > 0; i++) keeps running until i overflows, and while (true) runs for ever unless it reaches a break.
  • Empty loop: a loop with a semicolon straight after the heading, such as for (i = 0; i < 5; i++);. The body is empty, and the statement after it runs once.

Nested loops

A loop inside another loop is a nested loop. For each iteration of the outer loop, the inner loop runs completely. Nested loops are used for patterns and tables.

for (int i = 1; i <= 4; i++) {          // rows
    for (int j = 1; j <= i; j++)        // columns
        System.out.print("* ");
    System.out.println();
}

Output:

*
* *
* * *
* * * *

Number triangle:

for (int i = 1; i <= 4; i++) {
    for (int j = 1; j <= i; j++)
        System.out.print(j + " ");
    System.out.println();
}

Output:

1
1 2
1 2 3
1 2 3 4

Output questions: practise these

Q1. How many times does this loop run, and what is printed?

int x = 1;
while (x < 50)
    x = x * 3;
System.out.println(x);

Answer: x takes the values 1, 3, 9, 27 and 81. The loop runs 4 times and prints 81.

Q2. What is printed?

int k;
for (k = 10; k > 0; k -= 4);
System.out.println(k);

Answer: -2. The semicolon makes the loop body empty: k goes 10, 6, 2, −2, and then the loop stops. The print statement runs once, after the loop.

Solved program: reverse a number and check for a palindrome

import java.util.Scanner;

class Palindrome {
    public static void main(String args[]) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter a number: ");
        int n = sc.nextInt();
        int t = n, rev = 0;
        while (t > 0) {
            rev = rev * 10 + t % 10;
            t /= 10;
        }
        if (rev == n)
            System.out.println(n + " is a palindrome");
        else
            System.out.println(n + " is not a palindrome");
    }
}

Sample run: 1221 gives "1221 is a palindrome".

Exam tips

  1. When the question says "using a while loop", do not use a for loop. You lose marks even if the output is correct.
  2. Always copy the number into a temporary variable (t = n) before breaking it into digits, so the original is still available for the comparison.
  3. Use dry-run tables for every output question.

Continue with Math library methods and practise loops in our ICSE Class 9 solved programs.