Skip to content
Advertisement

Printing pyramid in Java on the console

How can I print a pyramid in Java like this

1
23
456
78910

My current code looks like this:

public class T {
    public static void main(String[] args) {
        int i, j, num = 1;
        int n = Integer.parseInt(args[0]);

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

If I try this removing declared i & j then it shows an array out of bounds exception However ‘i’ & ‘j’ are creating the problem. What should my code look like.

Advertisement

Answer

    int val=1;
    for(int i=0;i<6;i++){
        for(int j=1;j<i;j++){
             System.out.print(val);
            val++;
        }
        System.out.print("n");
    }

initially val is equal to 1 . Inside the first for loop i=0 and j with increase from 1, but when i=0 second for loop doesn’t run. then you get the first value as 1. Then it will point to new line.

When i=1,j still 1 so second for loop runs 1 time and print 2, because val has increment(val++). when j=2 in inside for loop it is not running only print the new value (3) of val there.

so on this will work

Advertisement