Write a program to print the following pattern:
*
* *
* * *
* * * *
* * * * *
Objective
Write a Java program to print a full pyramid star pattern.
Algorithm / Approach
- Use an outer loop (
i) to manage the rows (1 to 5). - Inside the outer loop, create a loop (
j) that prints decreasing spaces (from 5 down toi). - Create another inner loop (
k) that prints"* "(a star followed by a space), running from 1 up toi. - Print a newline after both inner loops finish.
Test.java
class Test {
public static void main(String[] a)
{
for(int i = 1; i<=5; i++) {
for(int j = 5; j>=i; j--) {
System.out.print(" ");
}
for(int k = 1; k<=i; k++) {
System.out.print("* ");
}
System.out.println();
}
}
}
Explanation of the Program
- A pyramid pattern requires two things per row: leading spaces to push the stars to the center, and the stars themselves.
- The first inner loop handles the padding. As the row number
iincreases, the number of spaces printed decreases. - The second inner loop prints the stars. By printing a star followed by a space
"* ", it naturally creates the spread-out pyramid shape without needing complex math for odd/even spacing.
Complexity
Time Complexity
O(n2)
Space Complexity
O(1)
Common Mistakes
- Forgetting the space after the star in
"* ", which would result in a right-aligned triangle instead of a centered pyramid.