Pyramid of Stars

This program prints a pyramid of stars.

Problem Statement

Write a Java program that prints a pyramid of stars with 5 rows.

Source Code

1 public class PyramidStars {
2 public static void main(String[] args) {
3 int n = 5;
4 for(int i=1; i<=n; i++) {
5 for(int j=i; j<n; j++) System.out.print(" ");
6 for(int k=1; k<=2*i-1; k++) System.out.print("*");
7 System.out.println();
8 }
9 }
10 }

Program Output

    *    
   ***   
  *****  
 ******* 
********* 

Explanation

The outer loop controls the rows, the first inner loop prints leading spaces to align stars centrally, and the second inner loop prints an odd number of stars (2*i-1) per row, together forming a symmetric pyramid.

Quick Links to Explore