Star Pyramid in Java: Explanation & Practice

Print a centered star pyramid

Problem summary

Print a centered pyramid of stars with n rows.

Starter code

public class Main {
    public static void main(String[] args) {
        int n = 3; // Test case 1
        
        // Print centered pyramid:
        //   *
        //  ***
        // *****
    }
}

Expected output and test cases

  • 3-row pyramid
      *
     ***
    *****
  • 2-row pyramid
     *
    ***
  • 4-row pyramid
       *
      ***
     *****
    *******

Hints

  1. Row i has (2*i - 1) stars
  2. Print (n - i) spaces before stars
  3. Outer loop for rows, inner loops for spaces and stars

Related Control Flow exercises

Practice all Control Flow exercises · Run this idea in the Java compiler