Course offer · HLD · LLD · System Design at ₹799 until 30 Nov (not interview packs)

Number Patterns in Java

Print a five-row number triangle in Java using nested for loops. Restart the inner counter at 1 each row; print a newline only after the row is complete.

BeginnerJava Loop ProgramsExample 15 of 25
number-patterns.java
1public class Main {
2 public static void main(String[] args) {
3 int n = 5;
4 for (int i = 1; i <= n; i++) {
5 for (int j = 1; j <= i; j++) {
6 System.out.print(j + " ");
7 }
8 System.out.println();
9 }
10 }
11}

Sample Output

1 
1 2 
1 2 3 
1 2 3 4 
1 2 3 4 5

At i=3, j visits 1,2,3 and prints those three values. The newline then starts row 4. Spaces after values are expected.

In this one

  • Give outer and inner loops different jobs
  • Reset a row counter
  • Place a newline after each row

How it works

  1. 1

    Set n to 5.

  2. 2

    Choose row i from 1 through n.

  3. 3

    Print j from 1 through i on that row.

  4. 4

    Print a newline after the row is complete.

Edge cases

One row

Set n = 1

Only 1 prints.

No rows

Set n = 0

The outer condition fails immediately and nothing prints.

What's going on

Print a triangle in which each row starts at 1 and ends at that row number. The first row has one value, the second has two, and so on. Pattern programs help you separate the job of choosing a row from the job of printing items inside it.

A nested loop is a loop inside another loop. Here the outer i loop chooses rows 1 through 5. For each row, the inner j loop starts again at 1 and prints up to i. After the inner loop ends, println moves to the next line.

Resetting j for every row is why the sequence starts at 1 each time. If you printed i instead of j, each row would repeat one number rather than count upwards. Keep the newline outside the inner loop, or every number will appear on a separate line and the triangle shape will be lost.

Quiz

Tap an option. The answer stays hidden until you pick.

Question 1

Which loop selects the row?

Pick an answer to check it.

Question 2

Where should println be placed?

Pick an answer to check it.

Questions people ask

Why does every row start at 1?

The inner loop declares a fresh j = 1 for each row.

How many numbers are in row 4?

Four, because j runs from 1 through 4.

What changes if I print i?

Row 3 would become 3 3 3 instead of 1 2 3.