Pattern Printing - Basic

Solve one Java logic problem at a time, then flip for the complete explanation and program.

0/180 Known filtered set
Difficulty
Read Full Guide Question: 1 of 180

Java Logic Development · Chapter 07 Companion Article

Pattern Printing - Basic

Fifteen star patterns — squares, triangles, pyramids, a diamond, hollow shapes, an X, and a plus — each derived from row-column conditions instead of memorized, so the same nested-loop thinking transfers to any new shape.

Overview

Pattern-printing problems are mainly used to test control over loops, conditions, row-column relationships, spacing, and boundary detection. The final pattern is visual, but the real skill is converting a shape into mathematical conditions.

Most basic pattern programs use:

  • An outer loop for rows.
  • An inner loop for columns, stars, or spaces.
  • Conditions to decide what should be printed at each position.
  • System.out.print() to stay on the same line.
  • System.out.println() to move to the next row.

Pattern Printing Fundamentals

For a pattern containing n rows: i usually represents the current row, j usually represents the current column or item position. Solid patterns mainly depend on loop limits. Right-aligned patterns require leading spaces. Hollow patterns require boundary conditions. Symmetrical patterns often require an odd size. Pyramid patterns combine spaces and stars.

Basic Nested Loop Structure

Java
for (int i = 1; i <= rows; i++) {
    for (int j = 1; j <= columns; j++) {
        System.out.print("* ");
    }
    System.out.println();
}

The outer loop determines how many lines are printed. The inner loop determines what appears on each line.

1. Square Star Pattern

A square contains the same number of rows and columns. For n = 5, every row contains five stars.

Pattern

Pattern
* * * * *
* * * * *
* * * * *
* * * * *
* * * * *

Logic

Run the outer loop n times. For every row, run the inner loop n times. Print one star during every inner-loop iteration. Both dimensions use the same value, which creates the square shape.

Java Program

Java
public class SquareStarPattern {
    public static void main(String[] args) {
        int n = 5;
        for (int i = 1; i <= n; i++) {
            for (int j = 1; j <= n; j++) {
                System.out.print("* ");
            }
            System.out.println();
        }
    }
}

Output

Output
* * * * *
* * * * *
* * * * *
* * * * *
* * * * *

Dry Run

For n = 5: row 1 prints 5 stars, row 2 prints 5 stars, the same process continues through row 5. Total stars printed = 5 × 5 = 25.

Complexity

  • Time: O(n²)
  • Space: O(1)

Common Mistake

Using different limits for rows and columns changes the square into a rectangle.

Interview Point

A square pattern is a simple way to demonstrate basic nested-loop understanding.

2. Rectangle Star Pattern

A rectangle uses different values for rows and columns. Example: rows = 4, columns = 6.

Pattern

Pattern
* * * * * *
* * * * * *
* * * * * *
* * * * * *

Logic

The outer loop controls height while the inner loop controls width. Unlike a square, the number of rows does not need to equal the number of columns.

Java Program

Java
public class RectangleStarPattern {
    public static void main(String[] args) {
        int rows = 4;
        int columns = 6;
        for (int i = 1; i <= rows; i++) {
            for (int j = 1; j <= columns; j++) {
                System.out.print("* ");
            }
            System.out.println();
        }
    }
}

Output

Output
* * * * * *
* * * * * *
* * * * * *
* * * * * *

Complexity

  • Time: O(rows × columns)
  • Space: O(1)

Key Learning

The important idea is separating vertical size from horizontal size.

3. Left Triangle Pattern

A left triangle increases the number of stars by one on every row. For row i, print exactly i stars.

Pattern

Pattern
*
* *
* * *
* * * *
* * * * *

Logic

For each row, stars = current row number. Therefore: row 1 → 1 star, row 2 → 2 stars, row 3 → 3 stars, row 5 → 5 stars.

Java Program

Java
public class LeftTrianglePattern {
    public static void main(String[] args) {
        int n = 5;
        for (int i = 1; i <= n; i++) {
            for (int j = 1; j <= i; j++) {
                System.out.print("* ");
            }
            System.out.println();
        }
    }
}

Output

Output
*
* *
* * *
* * * *
* * * * *

Dry Run

For row i = 4, the condition is j <= 4. Therefore four stars are printed.

Complexity

The total number of iterations is 1 + 2 + 3 + ... + n. Therefore:

  • Time: O(n²)
  • Space: O(1)

Common Mistake

Using j <= n prints the same number of stars on every row instead of forming a triangle.

4. Right Triangle Pattern

A right triangle is right-aligned. Each row contains leading spaces followed by stars.

Pattern

Pattern
        *
      * *
    * * *
  * * * *
* * * * *

Logic

For row i: spaces = n - i, stars = i.

RowSpacesStars
141
232
323
414
505

Because "* " occupies two character positions, " " is used for indentation.

Java Program

Java
public class RightTrianglePattern {
    public static void main(String[] args) {
        int n = 5;
        for (int i = 1; i <= n; i++) {
            for (int space = 1; space <= n - i; space++) {
                System.out.print("  ");
            }
            for (int star = 1; star <= i; star++) {
                System.out.print("* ");
            }
            System.out.println();
        }
    }
}

Output

Output
        *
      * *
    * * *
  * * * *
* * * * *

Complexity

  • Time: O(n²)
  • Space: O(1)

Interview Point

Right-aligned patterns test whether you can calculate both indentation and visible elements from the row number.

5. Inverted Left Triangle

The inverted left triangle starts with n stars and removes one star from every following row.

Pattern

Pattern
* * * * *
* * * *
* * *
* *
*

Logic

For row i: stars = n - i + 1. For n = 5: row 1 → 5, row 2 → 4, row 3 → 3, row 4 → 2, row 5 → 1.

Java Program

Java
public class InvertedLeftTriangle {
    public static void main(String[] args) {
        int n = 5;
        for (int i = 1; i <= n; i++) {
            for (int j = i; j <= n; j++) {
                System.out.print("* ");
            }
            System.out.println();
        }
    }
}

Output

Output
* * * * *
* * * *
* * *
* *
*

Alternative Loop

The inner loop can also be written as:

Java
for (int j = 1; j <= n - i + 1; j++) {
    System.out.print("* ");
}

Complexity

  • Time: O(n²)
  • Space: O(1)

6. Inverted Right Triangle

This pattern decreases the stars while increasing leading spaces.

Pattern

Pattern
* * * * *
  * * * *
    * * *
      * *
        *

Logic

For row i: spaces = i - 1, stars = n - i + 1. One quantity increases while the other decreases.

Java Program

Java
public class InvertedRightTriangle {
    public static void main(String[] args) {
        int n = 5;
        for (int i = 1; i <= n; i++) {
            for (int space = 1; space < i; space++) {
                System.out.print("  ");
            }
            for (int star = i; star <= n; star++) {
                System.out.print("* ");
            }
            System.out.println();
        }
    }
}

Output

Output
* * * * *
  * * * *
    * * *
      * *
        *

Complexity

  • Time: O(n²)
  • Space: O(1)

Common Mistake

Increasing spaces without decreasing stars produces an incorrectly shifted rectangle rather than an inverted triangle.

7. Pyramid Pattern

A pyramid combines decreasing leading spaces with an increasing odd number of stars.

Pattern

Pattern
    *
   ***
  *****
 *******
*********

Core Formula

For row i: spaces = n - i, stars = 2 × i - 1. The star sequence becomes 1, 3, 5, 7, 9.

Java Program

Java
public class PyramidPattern {
    public static void main(String[] args) {
        int n = 5;
        for (int i = 1; i <= n; i++) {
            for (int space = 1; space <= n - i; space++) {
                System.out.print(" ");
            }
            for (int star = 1; star <= 2 * i - 1; star++) {
                System.out.print("*");
            }
            System.out.println();
        }
    }
}

Output

Output
    *
   ***
  *****
 *******
*********

Dry Run

For row 4: spaces = 5 - 4 = 1, stars = 2 × 4 - 1 = 7. Result: *******

Why the Formula Works

Each new row expands by one position on the left and one on the right. That adds two stars: 1 → 3 → 5 → 7 → 9.

Complexity

  • Time: O(n²)
  • Space: O(1)

Interview Point

Remember the relationship 2 * i - 1. It appears frequently in pyramid and diamond problems.

8. Inverted Pyramid Pattern

An inverted pyramid begins at maximum width and gradually becomes narrower.

Pattern

Pattern
*********
 *******
  *****
   ***
    *

Logic

For row i: leading spaces = i - 1, stars = 2 × (n - i) + 1. For n = 5, stars are 9, 7, 5, 3, 1.

Java Program

Java
public class InvertedPyramidPattern {
    public static void main(String[] args) {
        int n = 5;
        for (int i = 1; i <= n; i++) {
            for (int space = 1; space < i; space++) {
                System.out.print(" ");
            }
            for (int star = 1; star <= 2 * (n - i) + 1; star++) {
                System.out.print("*");
            }
            System.out.println();
        }
    }
}

Output

Output
*********
 *******
  *****
   ***
    *

Complexity

  • Time: O(n²)
  • Space: O(1)

Key Learning

This is the reverse relationship of a normal pyramid: spaces increase, stars decrease by two.

9. Diamond Pattern

A diamond can be treated as two connected parts: a normal pyramid, then an inverted pyramid without repeating the middle row.

Pattern

Pattern
    *
   ***
  *****
 *******
*********
 *******
  *****
   ***
    *

Logic

For the upper half: spaces decrease, stars increase. For the lower half: spaces increase, stars decrease. The lower loop begins at n - 1 so the widest row is not printed twice.

Java Program

Java
public class DiamondPattern {
    public static void main(String[] args) {
        int n = 5;
        for (int i = 1; i <= n; i++) {
            for (int space = 1; space <= n - i; space++) {
                System.out.print(" ");
            }
            for (int star = 1; star <= 2 * i - 1; star++) {
                System.out.print("*");
            }
            System.out.println();
        }
        for (int i = n - 1; i >= 1; i--) {
            for (int space = 1; space <= n - i; space++) {
                System.out.print(" ");
            }
            for (int star = 1; star <= 2 * i - 1; star++) {
                System.out.print("*");
            }
            System.out.println();
        }
    }
}

Output

Output
    *
   ***
  *****
 *******
*********
 *******
  *****
   ***
    *

Total Rows

A diamond created with height parameter n contains 2n - 1 rows. For n = 5: 2 × 5 - 1 = 9 rows.

Complexity

  • Time: O(n²)
  • Space: O(1)

Common Mistake

Starting the second half from n prints the middle row twice.

10. Hollow Square Pattern

A hollow square prints stars only on its outer boundary.

Pattern

Pattern
* * * * *
*       *
*       *
*       *
* * * * *

Boundary Logic

Print a star when the current position belongs to: first row (i == 1), last row (i == n), first column (j == 1), or last column (j == n). Combined condition: i == 1 || i == n || j == 1 || j == n. Otherwise print spaces.

Java Program

Java
public class HollowSquarePattern {
    public static void main(String[] args) {
        int n = 5;
        for (int i = 1; i <= n; i++) {
            for (int j = 1; j <= n; j++) {
                if (i == 1 || i == n || j == 1 || j == n) {
                    System.out.print("* ");
                } else {
                    System.out.print("  ");
                }
            }
            System.out.println();
        }
    }
}

Output

Output
* * * * *
*       *
*       *
*       *
* * * * *

Why the Condition Works

Every cell on a square's border belongs to at least one of its four edges. Interior cells satisfy none of those conditions.

Complexity

  • Time: O(n²)
  • Space: O(1)

Interview Point

Hollow patterns are mainly boundary-condition problems rather than star-counting problems.

11. Hollow Rectangle Pattern

A hollow rectangle uses the same boundary idea as a hollow square, but row and column counts differ.

Pattern

Pattern
* * * * * *
*         *
*         *
* * * * * *

Logic

Print a star when i == 1 || i == rows || j == 1 || j == columns. Otherwise print spaces.

Java Program

Java
public class HollowRectanglePattern {
    public static void main(String[] args) {
        int rows = 4;
        int columns = 6;
        for (int i = 1; i <= rows; i++) {
            for (int j = 1; j <= columns; j++) {
                if (i == 1 || i == rows || j == 1 || j == columns) {
                    System.out.print("* ");
                } else {
                    System.out.print("  ");
                }
            }
            System.out.println();
        }
    }
}

Output

Output
* * * * * *
*         *
*         *
* * * * * *

Complexity

  • Time: O(rows × columns)
  • Space: O(1)

Edge Case

If either dimension is very small, such as one or two rows, little or no interior space exists. The boundary logic still works.

12. Hollow Triangle Pattern

A hollow left triangle prints the left edge, the diagonal edge, and the complete bottom edge.

Pattern

Pattern
*
* *
*   *
*     *
* * * * *

Position Rule

For row i and column j, print a star when j == 1 (left edge), j == i (diagonal edge), or i == n (bottom edge).

Java Program

Java
public class HollowTrianglePattern {
    public static void main(String[] args) {
        int n = 5;
        for (int i = 1; i <= n; i++) {
            for (int j = 1; j <= i; j++) {
                if (j == 1 || j == i || i == n) {
                    System.out.print("* ");
                } else {
                    System.out.print("  ");
                }
            }
            System.out.println();
        }
    }
}

Output

Output
*
* *
*   *
*     *
* * * * *

Dry Run

At row 4: j = 1 → star, j = 2 → space, j = 3 → space, j = 4 → star. Only both triangle edges remain visible.

Complexity

  • Time: O(n²)
  • Space: O(1)

Common Mistake

Checking only j == 1 || j == i leaves the bottom row hollow instead of closing the triangle.

13. Hollow Pyramid Pattern

A hollow pyramid prints only its two sloping boundaries and its bottom base.

Pattern

Pattern
    *
   * *
  *   *
 *     *
*********

Logic

Consider each row width as 2 * i - 1. Within that row, print stars only when j == 1 (left sloping boundary), j == 2 * i - 1 (right sloping boundary), or i == n (bottom edge). Leading spaces position the row correctly.

Java Program

Java
public class HollowPyramidPattern {
    public static void main(String[] args) {
        int n = 5;
        for (int i = 1; i <= n; i++) {
            for (int space = 1; space <= n - i; space++) {
                System.out.print(" ");
            }
            for (int j = 1; j <= 2 * i - 1; j++) {
                if (j == 1 || j == 2 * i - 1 || i == n) {
                    System.out.print("*");
                } else {
                    System.out.print(" ");
                }
            }
            System.out.println();
        }
    }
}

Output

Output
    *
   * *
  *   *
 *     *
*********

Why the Logic Works

The width of each pyramid row increases by two. The first and last positions of that width form the two diagonal edges.

Complexity

  • Time: O(n²)
  • Space: O(1)

Interview Point

Do not try to memorize the entire program. Identify three independent components: leading spaces, current row width, and boundary positions.

14. X Pattern

An X pattern is created using the two diagonals of a square matrix. For an n × n grid: main diagonal i == j, opposite diagonal i + j == n + 1.

Pattern

Pattern
*       *
  *   *
    *
  *   *
*       *

Logic Table for n = 5

Some star coordinates are: (1,1) and (1,5); (2,2) and (2,4); (3,3); (4,2) and (4,4); (5,1) and (5,5).

Java Program

Java
public class XPattern {
    public static void main(String[] args) {
        int n = 5;
        for (int i = 1; i <= n; i++) {
            for (int j = 1; j <= n; j++) {
                if (i == j || i + j == n + 1) {
                    System.out.print("* ");
                } else {
                    System.out.print("  ");
                }
            }
            System.out.println();
        }
    }
}

Output

Output
*       *
  *   *
    *
  *   *
*       *

Why i + j == n + 1 Works

For the opposite diagonal when n = 5: (1,5)1 + 5 = 6, (2,4)2 + 4 = 6, (3,3)3 + 3 = 6, (4,2)4 + 2 = 6, (5,1)5 + 1 = 6. Every coordinate has the same sum: n + 1.

Complexity

  • Time: O(n²)
  • Space: O(1)

Interview Point

The X pattern introduces matrix-coordinate thinking, which is useful beyond pattern questions.

15. Plus Pattern

A plus pattern places stars along the middle row and middle column. It is easiest to construct using an odd value of n. For n = 5, middle = n / 2. With zero-based indexing, middle = 2.

Pattern

Pattern
    *
    *
* * * * *
    *
    *

Logic

Print a star when i == middle || j == middle. This means the position belongs to either the middle row or the middle column.

Java Program

Java
public class PlusPattern {
    public static void main(String[] args) {
        int n = 5;
        int middle = n / 2;
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                if (i == middle || j == middle) {
                    System.out.print("* ");
                } else {
                    System.out.print("  ");
                }
            }
            System.out.println();
        }
    }
}

Output

Output
    *
    *
* * * * *
    *
    *

Why Odd Size Is Preferred

An odd-sized grid has exactly one center row and one center column. For n = 5, index 2 is the unique center. With an even value such as n = 6, there is no single central row and column, so the definition of the plus shape must be adjusted.

Complexity

  • Time: O(n²)
  • Space: O(1)

Understanding Solid and Hollow Patterns

Solid and hollow patterns require different reasoning.

Solid Pattern

Every valid position receives a star. Example:

Pattern
* * *
* * *
* * *

The main concern is deciding how many times the inner loop should run.

Hollow Pattern

Only boundary positions receive stars. Example:

Pattern
* * *
*   *
* * *

The main concern is determining whether the current (row, column) position belongs to an edge. This usually requires if conditions inside nested loops.

Important Pattern Formulas

PatternSpacesStars / Condition
Square0n
Rectangle0columns
Left Triangle0i
Right Trianglen - ii
Inverted Left Triangle0n - i + 1
Inverted Right Trianglei - 1n - i + 1
Pyramidn - i2 * i - 1
Inverted Pyramidi - 12 * (n - i) + 1
DiamondDepends on halfOdd-number sequence
Hollow Square0Four boundaries
Hollow Rectangle0Four boundaries
Hollow Triangle0Left, diagonal, bottom
Hollow Pyramidn - iTwo edges and base
X0Two diagonals
Plus0Middle row or column

Row and Column Thinking

Pattern problems become easier when the output is treated as a coordinate grid. For example, consider:

Pattern
*       *
  *   *
    *
  *   *
*       *

Instead of asking "How do I print an X?", ask "At which (i, j) positions should a star appear?" The answer becomes i == j || i + j == n + 1. This approach is especially effective for hollow shapes, diagonal patterns, X patterns, plus patterns, boxes, borders, and matrix-style patterns.

How to Derive a Pattern Instead of Memorizing It

Use the following process during practice or interviews.

Step 1: Count Rows

Determine how many output lines are required.

Step 2: Examine One Row at a Time

For each row, identify leading spaces, stars, internal spaces, and trailing content if any.

Step 3: Find the Relationship with Row Number

Ask whether each quantity increases, decreases, remains constant, or changes only at boundaries.

Step 4: Convert the Relationship into a Formula

Examples: stars = i, stars = n - i + 1, spaces = n - i, stars = 2 * i - 1.

Step 5: Handle Special Positions

For hollow or geometric patterns, determine whether the current cell is first row, last row, first column, last column, main diagonal, opposite diagonal, middle row, or middle column.

Step 6: Verify Using a Small Input

Values such as n = 3 or n = 5 make incorrect formulas easy to detect.

Choosing print() and println()

Pattern formatting depends heavily on these methods.

System.out.print()

Prints content without automatically moving to the next line. Example: System.out.print("* ");. Calling it repeatedly produces * * * * *.

System.out.println()

Moves the cursor to the next output line. It is normally called after the inner loop:

Java
for (int i = 1; i <= n; i++) {
    for (int j = 1; j <= n; j++) {
        System.out.print("* ");
    }
    System.out.println();
}

Placing println() inside the inner loop would incorrectly place each star on a separate line.

Understanding Spaces in Patterns

Spaces are part of the pattern logic, not merely decoration. Consider:

Pattern
*
* *
* * *

No indentation is required. But:

Pattern
    *
  * *
* * *

requires spaces before each row. If stars are printed using System.out.print("* "); then indentation may also need two spaces: System.out.print(" ");. If stars are printed without trailing spaces using System.out.print("*"); then one-space indentation is generally sufficient: System.out.print(" ");. Consistent character width prevents distorted output.

One-Based vs Zero-Based Pattern Loops

Both approaches are valid.

One-Based

Java
for (int i = 1; i <= n; i++) {
}

This style often makes formulas easier to understand: 2 * i - 1.

Zero-Based

Java
for (int i = 0; i < n; i++) {
}

This style is convenient when working with arrays, matrix indexes, middle positions, and coordinate conditions. For example, int middle = n / 2; is natural with zero-based indexing.

The important rule is consistency. Mixing one-based and zero-based formulas is a common source of off-by-one errors.

Using StringBuilder for Pattern Construction

For small interview examples, repeated System.out.print() calls are easy to understand. When building a pattern as a string, StringBuilder is more suitable. Example:

Java
public class PatternWithStringBuilder {
    public static void main(String[] args) {
        int n = 5;
        StringBuilder pattern = new StringBuilder();
        for (int i = 1; i <= n; i++) {
            for (int j = 1; j <= i; j++) {
                pattern.append("* ");
            }
            pattern.append(System.lineSeparator());
        }
        System.out.print(pattern);
    }
}

Output

Output
*
* *
* * *
* * * *
* * * * *

This approach separates pattern construction from output operations.

Taking Pattern Size from User Input

Hard-coded values are convenient for demonstrations. Real programs can accept the size from the user.

Java
import java.util.Scanner;

public class UserInputPattern {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter number of rows: ");
        int n = scanner.nextInt();
        if (n <= 0) {
            System.out.println("Number of rows must be positive.");
            return;
        }
        for (int i = 1; i <= n; i++) {
            for (int j = 1; j <= i; j++) {
                System.out.print("* ");
            }
            System.out.println();
        }
    }
}

For input 4, the pattern portion of the output is:

Output
*
* *
* * *
* * * *

Input validation prevents meaningless negative or zero-sized patterns when positive dimensions are required.

Pattern Printing Complexity

Most basic pattern programs are described as O(n²) because they process approximately n × n output positions. Examples: square n² stars, X checks n² positions, hollow square checks n² positions, plus checks n² positions.

Triangles do not execute exactly n² inner iterations. For example, 1 + 2 + ... + n = n(n + 1) / 2. However, asymptotically this is still O(n²).

Space Complexity

When the pattern is printed directly: O(1) auxiliary space. The loop variables consume constant extra memory regardless of n. When the complete output is stored in a StringBuilder, space complexity grows with the generated pattern size.

Output Complexity Matters

Pattern-printing programs physically generate characters. A program cannot generally print an n × n filled pattern in less than O(n²) output work because approximately n² characters or symbols must be produced. Therefore, optimization in pattern problems usually focuses more on correct formulas, clean conditions, avoiding unnecessary loops, and readable implementation rather than trying to reduce every pattern to linear time.

Common Pattern Printing Mistakes

1. Using println() Inside the Inner Loop

Incorrect:

Java
for (int j = 1; j <= n; j++) {
    System.out.println("* ");
}

Each star moves to a new line. Correct:

Java
for (int j = 1; j <= n; j++) {
    System.out.print("* ");
}
System.out.println();

2. Incorrect Loop Boundaries

Using < instead of <= can remove one row or one star. Example: for (int i = 1; i < n; i++) { } executes only n - 1 times.

3. Incorrect Space Count

For a right triangle or pyramid, incorrect indentation changes the entire shape. Always derive the space count from the current row instead of adjusting it by trial and error.

4. Mixing Character Widths

Using System.out.print("* "); with System.out.print(" "); can make right-aligned patterns appear shifted because the visible star unit has two characters while the space unit has one.

5. Printing the Diamond Center Twice

When joining two pyramids, the lower half should normally begin from n - 1.

6. Wrong Hollow Boundary Condition

Using logical AND instead of OR is a frequent mistake. Incorrect: i == 1 && i == n — a row cannot normally be both the first and last row. Correct boundary logic uses OR: i == 1 || i == n || j == 1 || j == n.

7. Forgetting the Bottom Boundary

Hollow triangle and hollow pyramid programs must explicitly print the final row completely.

8. Hard-Coding Individual Rows

Printing three separate System.out.println() calls with literal star strings may reproduce one fixed pattern, but it does not demonstrate pattern-generation logic. The solution should work for variable n.

Pattern Recognition Shortcuts

Instead of memorizing dozens of programs, recognize these relationships.

Increasing Pattern

Think: stars = i

Decreasing Pattern

Think: stars = n - i + 1

Right Alignment

Think: spaces + stars = n

Pyramid

Think: stars = odd numbers, therefore stars = 2 * i - 1

Hollow Shape

Think: "Which coordinates belong to the boundary?"

Diagonal Shape

Think: "Which row-column relationship identifies the diagonal?"

Important Conditions to Remember

These expressions are useful across many pattern problems.

PurposeCondition
First rowi == 1
Last rowi == n
First columnj == 1
Last columnj == n
Main diagonali == j
Opposite diagonali + j == n + 1
Zero-based opposite diagonali + j == n - 1
Middle rowi == n / 2
Middle columnj == n / 2
Triangle diagonali == j
Pyramid stars2 * i - 1
Increasing spacesi - 1
Decreasing spacesn - i

These should be understood as coordinate relationships rather than memorized blindly.

Pattern Comparison

PatternMain Skill Tested
SquareBasic nested loops
RectangleIndependent dimensions
Left TriangleRow-dependent loop limit
Right TriangleLeading-space calculation
Inverted Left TriangleDecreasing iteration count
Inverted Right TriangleIncreasing spaces and decreasing stars
PyramidOdd-number relationship
Inverted PyramidReverse pyramid relationship
DiamondCombining symmetric halves
Hollow SquareBoundary detection
Hollow RectangleBoundary detection with separate dimensions
Hollow TriangleMultiple edge conditions
Hollow PyramidWidth and boundary coordination
XDiagonal coordinate conditions
PlusCenter row and center column

Interview-Oriented Pattern Strategy

When an interviewer gives a new pattern, avoid immediately writing loops. First describe the pattern mathematically. For every row, determine:

  1. How many spaces come first?
  2. How many positions must be processed?
  3. Which positions contain stars?
  4. Does the star count increase or decrease?
  5. Is the shape based on boundaries or diagonals?
  6. Is the pattern symmetrical?
  7. Does the middle row need special handling?

For example, for:

Pattern
    *
   ***
  *****

You can immediately derive spaces = n - i and stars = 2 * i - 1. Once those relationships are correct, converting them to Java loops becomes straightforward.

Practice Variations

After understanding the basic versions, useful variations include:

  • Replace * with numbers.
  • Replace stars with letters.
  • Accept dimensions from user input.
  • Print patterns using a reusable method.
  • Reverse the orientation.
  • Print only borders.
  • Combine two basic patterns.
  • Use matrix-coordinate conditions.
  • Generate the pattern as a String.
  • Validate minimum and maximum dimensions.
  • Print multiple patterns using the same helper method.

These variations improve logic development without requiring completely different programming concepts.

Reusable Triangle Method

A basic pattern can be separated into a reusable method.

Java
public class ReusablePattern {
    public static void printLeftTriangle(int n) {
        for (int i = 1; i <= n; i++) {
            for (int j = 1; j <= i; j++) {
                System.out.print("* ");
            }
            System.out.println();
        }
    }
    public static void main(String[] args) {
        printLeftTriangle(5);
    }
}

Output

Output
*
* *
* * *
* * * *
* * * * *

Using methods keeps pattern logic separate from program setup and makes testing different sizes easier.

Pattern Printing Checklist

Before considering a pattern solution complete, verify:

  • Number of rows is correct.
  • Number of stars on each row is correct.
  • Leading spaces are correct.
  • Hollow boundaries are complete.
  • Symmetrical patterns are actually centered.
  • The center row is not duplicated.
  • Loop limits do not create extra rows or columns.
  • Input edge cases are handled where necessary.
  • Output spacing is consistent.
  • The program works for more than one valid size.
  • The logic is based on relationships rather than hard-coded output.

Chapter Quick Revision

  • Square: same rows and columns.
  • Rectangle: separate row and column counts.
  • Left triangle: stars increase with row number.
  • Right triangle: spaces decrease while stars increase.
  • Inverted left triangle: stars decrease.
  • Inverted right triangle: spaces increase while stars decrease.
  • Pyramid: stars follow 2 * i - 1.
  • Inverted pyramid: odd star counts decrease.
  • Diamond: pyramid plus reversed pyramid.
  • Hollow square: print only four boundaries.
  • Hollow rectangle: use separate row and column boundaries.
  • Hollow triangle: print left edge, diagonal edge, and base.
  • Hollow pyramid: print two sloping edges and base.
  • X: use the two diagonal conditions.
  • Plus: print the middle row and middle column.
  • Most basic pattern programs use nested loops.
  • Hollow and diagonal patterns depend strongly on row-column conditions.
  • Most basic patterns require O(n²) time.
  • Directly printed patterns normally require O(1) auxiliary space.

Question Hint