Print Right Pascal's Triangle Star Pattern in Java

Topic

The right Pascal's triangle is a common star pattern in Java interviews. It consists of two mirrored right-angle triangles—one increasing and the other decreasing. This pattern tests a candidate’s understanding of nested loops and basic logic flow.

In this program, we will print a pattern of stars (*) in a right-aligned triangular structure. This helps beginners practice nested loops and basic pattern logic.

Examples

Input: 5


*
* *
* * *
* * * *
* * * *
* * *
* *
*

Input: 3


*
* *
* * *
* *
*

Edge Case (Input: 1)


*

Interviewer Expectations

The interviewer is looking to assess:

  • Understanding of nested for loops
  • Ability to construct patterns row by row
  • Basic logical thinking and loop flow control
  • Clean code with proper variable usage

Approach

We divide the problem into two parts:

  1. Print the upper triangle (from 1 to n stars)
  2. Print the lower triangle (from n-1 to 1 stars)

Each triangle is built using nested loops. The outer loop handles the rows, and the inner loop prints the correct number of stars in that row.

Dry Run (Input = 3)


Upper triangle:
Row 1: print 1 star
Row 2: print 2 stars
Row 3: print 3 stars

Lower triangle:
Row 1: print 2 stars
Row 2: print 1 star

Java Program

public class RightPascalsTriangle {
  public static void main(String[] args) {
    int n = 5;

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

    // Lower triangle
    for (int i = n - 1; i >= 1; i--) {
      for (int j = 1; j <= i; j++) {
        System.out.print("* ");
      }
      System.out.println();
    }
  }
}
*
* *
* * *
* * * *
* * * *
* * *
* *
*

Possible Followup Questions with Answers

Q1: How do you print an inverted right Pascal's triangle?

Swap the order: first print the decreasing triangle, then the increasing triangle.

Q2: How can you take input from the user for the number of rows?

Scanner sc = new Scanner(System.in);
System.out.print("Enter number of rows: ");
int n = sc.nextInt();

Q3: How to print numbers instead of stars?

Replace System.out.print("* ") with System.out.print(j + " ").

Q4: What is the time complexity of this pattern?

O(n²), since for each row up to n, we print up to n elements in the worst case.


Comments

💬 Please keep your comment relevant and respectful. Avoid spamming, offensive language, or posting promotional/backlink content.
All comments are subject to moderation before being published.


Loading comments...