LIWA

Nested for loops

ICSE Class 9 · Computer Applications · Chapter 10

What this chapter covers

Key points

Questions answered

Define a nested loop. Which loop is called the outer loop and which the inner loop?
A nested loop is a loop placed inside the body of another loop. The loop that contains the other is the outer loop, and the loop written inside its body is the inner loop.
In a nested loop, the outer loop runs 6 times and the inner loop runs 8 times on each pass. How many times does the inner loop body run in all?
6 × 8 = 48 times, because the inner loop runs all 8 of its iterations on every one of the 6 passes of the outer loop.
How many times does the inner body run in `for (int i = 1; i <= 5; i++) for (int j = i; j <= 5; j++) c++;`?
15 times. The inner loop runs 5, 4, 3, 2 and 1 times for `i` = 1 to 5, and 5 + 4 + 3 + 2 + 1 = 15.
Give the output: `for (int i = 1; i <= 3; i++) { for (int j = 1; j <= i; j++) System.out.print(i * j + " "); System.out.println(); }`
Three rows: `1`, then `2 4`, then `3 6 9`.
Give the output: `for (int i = 1; i <= 4; i++) { for (int j = 1; j <= 4; j++) { if (j > i) break; System.out.print(j); } System.out.println(); }`
Four rows: `1`, `12`, `123` and `1234`. The `break` ends only the inner loop once `j` passes `i`, and the outer loop goes on to the next row.
Give the output: `for (int i = 1; i <= 3; i++) { for (int j = 1; j <= 3; j++) { if ((i + j) % 2 != 0) continue; System.out.print(i * 10 + j + " "); } System.out.println(); }`
Three rows: `11 13`, then `22`, then `31 33`. Whenever i + j is odd, `continue` skips the print for that column only.
State the effect of a `break` written (a) inside the inner loop and (b) in the outer loop but outside the inner loop.
(a) It ends only the inner loop; the outer loop continues with its next iteration. (b) It ends the outer loop, and with it the whole nested loop.
Write the nested loops to print the pattern `5` / `5 4` / `5 4 3` / `5 4 3 2` / `5 4 3 2 1`.
`for (int i = 1; i <= 5; i++) { for (int j = 5; j >= 6 - i; j--) System.out.print(j + " "); System.out.println(); }` Row `i` counts down from 5 and stops at 6 - i, so it has `i` numbers.

Past board exam questions

ICSE 2027 sample paper · 15 marks

(i) Define a class “pattern” to print the following format using nested for loop only. ``` 1*2*3*4*5* 1*2*3*4*5* 1*2*3*4*5* 1*2*3*4*5* ``` (ii) Name three iteration statements in Java.

Show answer
(i) ```java class pattern { public static void main(String args[]) { int r, c; for (r = 1; r <= 4; r++) { for (c = 1; c <= 5; c++) { System.out.print(c + "*"); } System.out.println(); } } } ``` Variable description: r – int, outer loop counter for the 4 rows; c – int, inner loop counter printing 1 to 5, each followed by *. (ii) The iteration statements in Java are for, while and do-while.