Pattern Programs
Pattern programs build strong control over nested loops, which is a skill used throughout more advanced programming, including grid-based logic and 2D array processing.
Why practice these?
Pattern programs build strong control over nested loops, which is a skill used throughout more advanced programming, including grid-based logic and 2D array processing.
Program 1: Right-Angled Triangle of Stars
javapublic class TrianglePattern { public static void main(String[] args) { int rows = 5; for (int i = 1; i <= rows; i++) { for (int j = 1; j <= i; j++) { System.out.print("*"); } System.out.println(); } } }
Output:
*
**
***
****
*****Program 2: Number Pyramid
javapublic class NumberPyramid { public static void main(String[] args) { int rows = 4; for (int i = 1; i <= rows; i++) { for (int j = 1; j <= i; j++) { System.out.print(j + " "); } System.out.println(); } } }
Output:
1
1 2
1 2 3
1 2 3 4 Program 3: Inverted Star Triangle
javapublic class InvertedTriangle { public static void main(String[] args) { int rows = 4; for (int i = rows; i >= 1; i--) { for (int j = 1; j <= i; j++) { System.out.print("*"); } System.out.println(); } } }
Output:
****
***
**
*Key Points to Remember
- Pattern programs almost always use a nested loop — an outer loop for rows and an inner loop for columns.
- Practicing patterns strengthens the ability to trace through nested loop logic manually, step by step.
- Common variations include triangles, pyramids, diamonds, and number/character-based patterns.