A Pyramid Number Pattern is a popular pattern-printing problem in Java that helps beginners understand nested loops, spacing, and number manipulation. In this pattern, the numbers first increase from left to right and then decrease symmetrically, forming a pyramid shape.
- The third loop prints numbers in decreasing order.
- The number of rows determines the height of the pyramid.
- Helps in understanding loop control and pattern generation.
Illustrations:
Input: Rows = 5
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
Approach
- For loop will be used to print each row in the pyramid.
- Inside the for loop we will use two loops :
- One loop is used to print the spaces
- The second loop will be used to print the numbers.
Example: Program to Print the Pyramid pattern
public class GFG {
public static void main(String[] args) {
int rows = 5;
for (int i = 1; i <= rows; i++) {
// Print leading spaces
for (int j = i; j < rows; j++) {
System.out.print(" ");
}
// Print increasing numbers
for (int j = 0; j < i; j++) {
System.out.print((i + j) + " ");
}
// Print decreasing numbers
for (int j = i - 2; j >= 0; j--) {
System.out.print((i + j) + " ");
}
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
Explanation: The program uses an outer loop to print each row of the pyramid. For every row, it first prints the required spaces, then prints numbers in increasing order, followed by numbers in decreasing order to create a symmetric pyramid pattern