How to Print a Number Pyramid in Java

The following Java program prints a sequential number pyramid in Java. The output of the program is given below.

 

    1 
   2 3 
  4 5 6 
 7 8 9 10 
11 12 13 14 15 
 
/**
 * Prints number pyramid Java
 * @author jj
 */
public class NumberPyramid {
    public static void main(String[] args) {
        int rows = 5; // number of rows for pyramid
        for(int i=1;i<=rows;i++) {
            for(int k=rows-i;k>=1;k--) {
                System.out.print(" ");
            }
            for(int j=1;j<=i;j++) {                
                System.out.print(i*(i-1)/2+j+" ");
            }
            System.out.println();
        }
    }
}

Do you have a programming problem that you are unable to solve? Please send us your problem and we will publish the solution on this site within 48 hours! Please email us.


Leave a Reply