1. Introduction
In this post, we will explore how to write a Java program that prints a pyramid pattern using asterisks (*). This type of program is a useful for beginners, offering a practical way to learn nested loops and control structures in Java. By creating a pyramid, we will understand how to manipulate output on the console to create shapes and patterns, a fundamental skill in programming that can be applied in various contexts.
2. Program Steps
1. Initialize the necessary variables for the number of rows in the pyramid.
2. Use a for loop to iterate over the rows of the pyramid.
3. Inside the loop, use two additional for loops: one to print spaces and another to print asterisks (*), thereby forming the pyramid shape.
4. Compile and run the program to see the pyramid pattern printed on the console.
3. Code Program
public class PyramidPattern {
public static void main(String[] args) {
int rows = 5; // Number of pyramid rows
for(int i = 0; i < rows; i++) { // Loop for each row
for(int j = rows - i; j > 1; j--) { // Loop for spaces
System.out.print(" "); // Printing space
}
for(int k = 0; k <= i; k++) { // Loop for asterisks
System.out.print("* "); // Printing asterisk and space
}
System.out.println(); // New line after each row
}
}
}
Output:
* * * * * * * * * * * * * * *
Explanation:
1. The program initializes with a fixed number of rows (rows = 5).
2. It uses a for loop to iterate through each row. The iteration starts from 0 to maintain the proper count for spaces and asterisks.
3. For each row, a nested for loop first prints the required number of spaces to align the asterisks in a pyramid shape. The number of spaces decreases as the row number increases (for(int j = rows - i; j > 1; j--)).
4. Another nested for loop prints the asterisks (*) and a space to form the pyramid pattern. The number of asterisks increases with each row (for(int k = 0; k <= i; k++)).
5. After printing the required spaces and asterisks for a row, a newline character (System.out.println()) is used to move to the next line.
6. This process repeats until the pyramid pattern is completed for the specified number of rows.
Comments
Post a Comment
Leave Comment