Back to the 2026 paper

Module 1: Introduction to Java

20267m

Construct a Java program that prints a triangular pattern of numbers and analyse how the for loop controls the number of rows and columns.

Worked SolutionAI Assisted

Number triangle using nested for loops

public class Triangle {
    public static void main(String[] args) {
        int rows = 5;
        for (int i = 1; i <= rows; 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
1 2 3 4 5

The outer loop controls rows (i = 1 to rows). The inner loop prints i numbers on row i; println() moves to the next line. There are (1+2+\cdots+n=n(n+1)/2) printed values, so time complexity is O(n²) and auxiliary space is O(1).

Similar questions

Student FinanceWeb Platform

Pocketly — Personal Finance for Students

Keep your hostel and college expenses under control. Track accounts, log spending in seconds, and stay within your monthly budget.