Print K Shape Star Pattern in Java

Topic

In this program, we will print a star pattern that looks like the letter K. Pattern printing is commonly asked in Java interviews to test the candidate's understanding of loops and nested loops. The 'K' shape is formed by printing stars in two parts: the upper diagonal and the lower diagonal, aligned with a common vertical line.

Examples

Input: Number of rows = 5

*   *
*  *
* *
*  *
*   *

Input: Number of rows = 7

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

Edge Case: Rows = 1

*

Even with just 1 row, the program should handle the pattern gracefully.

Interviewer Expectations

The interviewer wants to see if you understand how to:

  • Use nested loops effectively
  • Handle symmetrical and diagonal printing
  • Think through row-column based logic
  • Write clean, readable code with good variable naming

Approach

We divide the pattern into two parts:

  1. For the upper half (including the center), print stars at positions (i, 0) and (i, n - i - 1)
  2. For the lower half, continue printing stars at (i, 0) and (i, i)

Dry Run: n = 5

Row 0: star at 0 and 4 → *   *
Row 1: star at 0 and 3 → *  *
Row 2: star at 0 and 2 → * *
Row 3: star at 0 and 1 → *  *
Row 4: star at 0 and 0 → *   *

Java Program

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

Possible Followup Questions with Answers

Q1: How do you make the pattern larger or dynamic?

Change the value of n or read it using Scanner from user input.

Q2: How to print a reverse K pattern?

Reverse the row condition from top-to-bottom to bottom-to-top. This may involve flipping the diagonal formula to j == i.

if (j == 0 || j == i) {
    System.out.print("*");
}

Q3: Can we print the same using a single loop?

It is possible but would require string manipulation instead of character-by-character printing, which complicates readability for beginners.


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...