Write a Java program that prints a pyramid pattern of numbers.
This Java program prints a pyramid pattern of numbers. The program uses nested loops to print spaces and numbers. Here’s the breakdown of the code:
class Main {
public static void main(String[] args) {
int rows=5;
for(int i=1;i<=rows;i++){
for(int j=i;j<=rows;j++){
System.out.print(" ");
}
for(int k=1;k<=(2*i-1);k++){
System.out.print(k+" ");
}
System.out.println();
}
}
}
Output:
1
1 2 3
1 2 3 4 5
1 2 3 4 5 6 7
1 2 3 4 5 6 7 8 9
Code Breakdown
int rows = 5;
This sets the number of rows for the pyramid. The number of rows can be adjusted to print a bigger or smaller pyramid.
Outer Loop (for (int i = 1; i <= rows; i++))
The outer loop controls the number of rows. It runs from 1 to 5 (in this case).
First Inner Loop (for (int j = i; j <= rows; j++))
This loop prints spaces before the numbers to form the pyramid shape.
As i increases, the number of spaces decreases, and the pyramid narrows as it goes down.
Second Inner Loop (for (int k = 1; k <= (2 * i – 1); k++))
This loop prints the numbers in each row. The number of numbers printed increases with each row.
For row i, it prints 2*i – 1 numbers.
System.out.println();
After printing the numbers in a row, this statement moves to the next line.
Key Points:
Spaces: In each row, the number of spaces decreases as the row number (i) increases, which gives the pyramid shape.
Numbers: The number of numbers printed in each row increases. For the ith row, the number of numbers printed is 2*i – 1.
Adjustable Size: You can change the rows variable to adjust the size of the pyramid. The height and width of the pyramid will increase accordingly.