Creating a pyramid of numbers in Java is a common task often used to practice loops and nested loops. The pyramid pattern typically consists of numbers arranged in rows with increasing size, making it look like a pyramid. Below is the code to create a pyramid of numbers, along with an explanation of how it works.
Example Code: Pyramid of Numbers
public class NumberPyramid {
public static void main(String[] args) {
int n = 5; // Number of rows for the pyramid
// Outer loop for the rows
for (int i = 1; i <= n; i++) {
// Print spaces before numbers for pyramid alignment
for (int j = 1; j <= n - i; j++) {
System.out.print(" ");
}
// Print numbers in ascending order
for (int k = 1; k <= i; k++) {
System.out.print(k + " ");
}
// Move to the next line after each row
System.out.println();
}
}
}
Explanation:
- Outer Loop (
for (int i = 1; i <= n; i++)
):
- This loop controls the number of rows in the pyramid. In this example,
n = 5
, so the pyramid will have 5 rows. - Each iteration of this loop represents a new row.
- Inner Loop 1: Spaces (
for (int j = 1; j <= n - i; j++)
):
- This loop prints spaces before the numbers to create the pyramid shape.
- The number of spaces decreases as you move to the next row (
n - i
spaces).
- Inner Loop 2: Numbers (
for (int k = 1; k <= i; k++)
):
- This loop prints the numbers in ascending order for each row. The number of digits printed corresponds to the row number
i
.
- System.out.println():
- This moves the cursor to the next line after printing each row to ensure the pyramid grows downward.
Output:
For n = 5
, the output will look like this:
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
Explanation of Pyramid Structure:
- First row: 4 spaces followed by “1”.
- Second row: 3 spaces followed by “1 2”.
- Third row: 2 spaces followed by “1 2 3”.
- Fourth row: 1 space followed by “1 2 3 4”.
- Fifth row: 0 spaces followed by “1 2 3 4 5”.
Modifying the Number of Rows:
You can change the value of n
in the code to modify the height of the pyramid. For example, if n = 6
, the pyramid will have 6 rows:
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
1 2 3 4 5 6
Conclusion
This approach allows you to create a number pyramid in Java using simple loops. Feel free to modify the pattern, such as printing numbers in reverse order or creating different shapes, to expand your understanding of loops and string manipulation in Java.
For any further queries or modifications, feel free to contact Divi Tech HR Solution (info@divisolutions.in). Don’t forget to like and comment on this blog post if you found it helpful!
0 Comments