Skip to main content

ProwessApps

Learn · Practice · Excel

Write a program to print the following pattern:
*
* *
* * *
* * * *
* * * * *

Java Code Example — Pattern Programs

ADVERTISEMENT

Write a program to print the following pattern:
*
* *
* * *
* * * *
* * * * *

Objective

Write a Java program to print a full pyramid star pattern.

Algorithm / Approach

  1. Use an outer loop (i) to manage the rows (1 to 5).
  2. Inside the outer loop, create a loop (j) that prints decreasing spaces (from 5 down to i).
  3. Create another inner loop (k) that prints "* " (a star followed by a space), running from 1 up to i.
  4. 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 i increases, 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.
ADVERTISEMENT