Learn how to print Pyramid Star Pattern in Java using nested loops. This Java program creates a full pyramid of stars (*) based on the number of rows entered by the user.
Code Explanation (Step-by-Step)
- Create a Scanner class object to accept user input.
- Read the number of rows using the sc.nextInt() method.
- Use an outer for loop to iterate through each row.
- Use the first inner loop to print the required leading spaces.
- Use the second inner loop to print stars in each row.
- The first row contains 1 star, and each subsequent row contains 2 more stars than the previous row (2 * i – 1).
- Print a new line after each row to form the pyramid shape.
import java.util.Scanner;
public class PyramidStar {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the number of rows:");
int row = sc.nextInt();
for (int i = 1; i <= row; i++) {
// Print leading spaces
for (int j = (row - i); j >= 1; j--) {
System.out.print(" ");
}
// Print stars
for (int k = 1; k <= (2 * i - 1); k++) {
System.out.print("* ");
}
System.out.println();
}
sc.close();
}
}
Output:-
Enter the number of rows:- 6
*
* * *
* * * * *
* * * * * * *
* * * * * * * * *
* * * * * * * * * * *
Java 8 Program to Print Pyramid Star Pattern
import java.util.Scanner;
import java.util.stream.IntStream;
public class PyramidStarPattern {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter the number of rows: ");
int rows = sc.nextInt();
IntStream.rangeClosed(1, rows).forEach(i -> {
IntStream.range(0, rows - i)
.forEach(j -> System.out.print(" "));
IntStream.rangeClosed(1, (2 * i - 1))
.forEach(k -> System.out.print("* "));
System.out.println();
});
sc.close();
}
}
Here are some Java-related programs that will help you understand Java concepts better:
FAQ
What is a Pyramid Star Pattern in Java?
A Pyramid Star Pattern is a pattern program that prints stars in a pyramid shape using nested loops. Each row contains more stars than the previous row.
Which loop is used to print a Pyramid Star Pattern?
Nested for loops are commonly used. One loop controls rows, while inner loops print spaces and stars.
Why do we use (2 * i – 1) in the program?
This formula generates odd numbers (1, 3, 5, 7, …), which helps create the pyramid shape.
Can we print a Pyramid Pattern using a while loop?
Yes, a Pyramid Star Pattern can also be implemented using while loops instead of for loops.
What is the time complexity of a Pyramid Star Pattern program?
The time complexity is O(n²) because nested loops are used.