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 right-angled triangle star pattern.

Algorithm / Approach

  1. Use an outer for loop (i) to manage the rows, running from 1 to 5.
  2. Inside the outer loop, use an inner for loop (j) to manage the columns.
  3. Run the inner loop from 1 up to the current row number i.
  4. In the inner loop, print a star "*" without a newline.
  5. After the inner loop completes, print a newline character to move to the next row.
Test.java
class Test {
 public static void main(String[] a)
 {
  for(int i = 1; i<=5; i++) {
   for(int j = 1; j<=i; j++) {
    System.out.print("*");
   }
   System.out.println();
  }
 }
}

Explanation of the Program

  • This is the most fundamental pattern program, demonstrating how nested loops work.
  • The outer loop controls how many rows are printed (5 rows in this case).
  • The inner loop uses the outer loop's variable i as its boundary. On row 1, it prints 1 star. On row 2, it prints 2 stars, and so on.
  • The System.out.println() at the end of the outer loop ensures the next row starts on a fresh line.

Complexity

Time Complexity O(n2) - Where n is the number of rows.
Space Complexity O(1)

Common Mistakes

  • Using println() instead of print() for the stars, which would cause every single star to appear on a new line instead of forming a triangle.
  • Making the inner loop run to 5 every time instead of i, resulting in a 5x5 square block of stars instead of a triangle.
ADVERTISEMENT