Skip to content
Related Articles

Related Articles

Java Program to Print Pyramid Number Pattern
  • Last Updated : 17 Mar, 2021

Approach:

  1. For loop will be used to print each row in the pyramid.
  2. Inside the for loop we will use two loops :
  3. One loop is used to print the spaces
  4. The second loop will be used to print the numbers.

Illustrations:

A pyramid number pattern of row size r = 5 would look like:
        1 
      2 3 2 
    3 4 5 4 3 
  4 5 6 7 6 5 4 
5 6 7 8 9 8 7 6 5
A pyramid number pattern of row size r = 4 would look like:
      1 
    2 3 2 
  3 4 5 4 3 
4 5 6 7 6 5 4 

Implementation:

Java




// Java Program to Print the Pyramid pattern
  
// Main class
public class GFG {
  
    // Main driver method
    public static void main(String[] args)
    {
  
        // The variable count1 and count2 used to
        // keep track of the column number
  
        // Custom input of rows = N
        // Say N = 6
        int rows = 6, k = 0, count1 = 0, count2 = 0;
  
        // Iterating using for loop
        for (int i = 1; i <= rows; i++) {
  
            // This for loop is used to print the required
            // spaces
            for (int space = 1; space <= rows - i;
                 space++) {
  
                // Print white spaces
                System.out.print("  ");
                count1++;
            }
  
            // Condition check in while loop  to
            // print the numbers in the pyramid
            while (k != 2 * i - 1) {
  
                // Case 1: When the column count is less
                // than the row size then print i+k
                if (count1 <= rows - 1) {
                    System.out.print((i + k) + " ");
  
                    // Increment the first counter
                    count1++;
                }
  
                // Case 2: When the column count is greater
                // than
                //  the row size then print i+k-2*count
                else {
  
                    // Increment the second counter
                    count2++;
                    System.out.print((i + k - 2 * count2)
                                     + " ");
                }
  
                k++;
            }
            count2 = count1 = k = 0;
  
            // By now done operations over first row so
            // new line
            System.out.println();
        }
    }
}
Output
          1 
        2 3 2 
      3 4 5 4 3 
    4 5 6 7 6 5 4 
  5 6 7 8 9 8 7 6 5 
6 7 8 9 10 11 10 9 8 7 6 

Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.




My Personal Notes arrow_drop_up
Recommended Articles
Page :