Putting one loop inside another — a nested loop — lets you work with grids, patterns and tables. Combined with the number tricks here, these are the most common ICSE Class 9 programs.
1Nested loops & patterns
A nested loop is a loop inside another loop. The outer loop usually controls the rows and the inner loop the columns:
// a right-angled triangle of stars
for (int i = 1; i <= 4; i++) { // rows
for (int j = 1; j <= i; j++) // columns (grows each row)
System.out.print("* ");
System.out.println(); // newline after each row
}Output:
* * * * * * * * * *
i) to switch between rectangles and triangles.- A nested loop is a loop inside a loop; the outer controls rows, the inner controls columns.
- For each outer pass, the inner loop runs completely.
- A fixed inner limit gives a rectangle; an inner limit of i gives a triangle.
2Mathematical series
A loop can build a series — adding or multiplying a chain of terms with a single variable:
// Sum: 1 + 2 + 3 + ... + n int sum = 0; for (int i = 1; i <= n; i++) sum = sum + i; // Sum of squares: 1² + 2² + ... + n² int s = 0; for (int i = 1; i <= n; i++) s = s + i * i;
- A loop builds a series by updating an accumulator with each term.
- Start the accumulator at 0 for a sum, 1 for a product.
- Work out the general term (i, i*i, etc.) and add/multiply it each pass.
3Classic number programs
These come up again and again in exams. Each uses a loop and a check:
| Program | A number is … if |
|---|---|
| Prime | It has exactly two factors: 1 and itself |
| Composite | It has more than two factors (not prime) |
| Perfect | The sum of its factors (excluding itself) equals the number (6 = 1+2+3) |
| Armstrong | The sum of each digit cubed equals the number (153 = 1³+5³+3³) |
| Palindrome | It reads the same reversed (121, 1331) |
| Fibonacci | Series where each term is the sum of the previous two (0,1,1,2,3,5,8…) |
// count factors to test for prime
int count = 0;
for (int i = 1; i <= n; i++)
if (n % i == 0) count++;
if (count == 2) System.out.println("Prime");n % i == 0, and breaking a number into digits with n % 10 (last digit) and n / 10 (drop the last digit).- Prime = exactly two factors; composite = more than two; perfect = factor-sum (excluding itself) equals the number.
- Armstrong = sum of digit-cubes equals the number; palindrome = same reversed; Fibonacci = each term is the sum of the previous two.
- Core tricks: factors via n % i == 0; digits via n % 10 (last digit) and n / 10 (remove it).
★ Practical: patterns & numbers
In BlueJ, write programs that:
- Print a 4×4 rectangle of stars, then a right-angled triangle of stars.
- Find the sum 1 + 2 + 3 + ... + n for an entered n.
- Check whether an entered number is prime (count its factors).
- Check whether an entered number is a palindrome (reverse it and compare).
Ready for the chapter test?
Answer 5 questions. Score 60% or more to mark this chapter complete.
Start the test →💡 Log in to save your progress and earn the certificate.