Program to print pyramid numbers in java

Program to print pyramid numbers in java:

Pyramid numbers are basically something like matrix to print the numbers in rows and columns. It has been a common question from beginner to intermittent level developers in many interviews.

Logic in Overview:

1. Define the number of rows to print the pyramid.
2. Use nested loop to print the rows and columns.
3. First outer loop takes the count from the above defined variable.
4. Second inner loop takes the count from the outer loop.
5. Use print() method instead of println() to get the desired pyramid output.
6. Empty println() outside the inner loop to move to next new line.

Program to print pyramid numbers in java:

package com.ngdeveloper;

public class PyramidNumbers {
public static void main(String[] args) {
// Defining the number of rows 
int numOfRows = 5;
// Nested loop used here to print the pyramid numbers 
for (int i = 0; i <= numOfRows; i++) {
for (int j = 0; j < i; j++) {
// Note we used print not println here
System.out.print(j);
} // println for empty line System.out.println();
}
}
}

Console Output:

0
01
012
0123
01234

Program to print pyramid stars in java:

package com.ngdeveloper;

public class PyramidNumbers {

    public static void main(String[] args) {
// Defining the number of rows
        int numOfRows = 5;

// Nested loop used here to print the pyramid numbers
        for (int i = 0; i <= numOfRows; i++) {
            for (int j = 0; j < i; j++) {
// Note we used print not println here
                System.out.print("*");
            }
// println for empty line
            System.out.println();
        }
    }
}

Console Output:

*
**
***
****
*****

If you see above, we have defined the number of rows as 5 so pyramid printed output with 5 rows. Whenever you see a question with pyramid outputs, then first remember to use nested loops and think a little about the core business logic.

Leave a Reply