- 1Print Right Triangle Star Pattern in Java
- 2Print Inverted Right Triangle Star Pattern
- 3Print Mirrored Right Triangle Star Pattern in Java
- 4Print Inverted Mirrored Right Triangle Star Pattern
- 5Print Right Pascal's Triangle Star Pattern in Java
- 6Print K Shape Star Pattern in Java
- 7Print Mirrored Right Pascal's Triangle Pattern in Java
- 8Print Full Reverse K Star Pattern in Java
- 9Print Pyramid Star Pattern in Java
- 10Print Inverted Pyramid Star Pattern in Java
- 11Print Diamond Star Pattern in Java
- 12Print Hollow Diamond Star Pattern in Java
- 13Print Sandglass Star Pattern in Java
- 14Print Butterfly Star Pattern in Java
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:
- Print the upper triangle (from 1 to n stars)
- 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.
Next Topic ⮕Print K Shape Star Pattern in Java
Comments
Loading comments...