Open In App
Related Articles

Java Program to Print Pyramid Number Pattern

Improve Article
Improve
Save Article
Save
Like Article
Like

Here we are getting a step ahead in printing patterns as in generic we usually play with columnar printing in the specific row keep around where elements in a row are either added up throughout or getting reduced but as we move forward we do start playing with rows which hold for outer loop in our program.

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 

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.

Implementation:

Java




// Java Program to Print the Pyramid pattern
 
// Main class
public class GFG {
 
    // Main driver method
    public static void main(String[] args)
    {
        int num = 5;
        int x = 0;
 
        // Outer loop for rows
        for (int i = 1; i <= num; i++) {
            x = i - 1;
 
            // inner loop for "i"th row printing
            for (int j = i; j <= num - 1; j++) {
 
                // First Number Space
                System.out.print(" ");
 
                // Space between Numbers
                System.out.print("  ");
            }
 
            // Pyramid printing
            for (int j = 0; j <= x; j++)
                System.out.print((i + j) < 10
                                     ? (i + j) + "  "
                                     : (i + j) + " ");
 
            for (int j = 1; j <= x; j++)
                System.out.print((i + x - j) < 10
                                     ? (i + x - j) + "  "
                                     : (i + x - j) + " ");
 
            // By now we reach end for one row, so
            // new line to switch to next
            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  

Time complexity: O(N^2) where N is given row size.
Auxiliary space: O(1), using constant extra space.


Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now!

Last Updated : 06 Sep, 2022
Like Article
Save Article
Previous
Next
Similar Reads
Complete Tutorials