Butterfly Star Pattern in Java Using Nested Loops

⚡ Direct Answer & Key Takeaway

The Butterfly Star Pattern renders symmetrical upper and lower halves across 2 * n rows. Each row i (climbing 1 to n in the upper phase, then stepping n down to 1 in the lower phase) contains three consecutive inner segments: i left-wing stars, 2 * (n - i) central gap spaces, and i right-wing stars. Every row preserves a constant total width of 2 * n characters.

1. Wing-Gap-Wing Geometry and the 2*(n - i) Formula

Although the Butterfly Star Pattern looks intricate, every single line maintains an identical rectangular width of 2 * n columns. On row i, the left wing occupies i columns on the far left and the right wing occupies i columns on the far right, consuming 2 * i star positions altogether. Subtracting those stars from the total row width leaves 2 * n - 2 * i = 2 * (n - i) empty positions right in the middle. Consequently, each outer iteration executes three sequential inner loops: i stars for the left wing, spaces = 2 * (n - i) spaces for the central void, and i stars for the right wing. Because the upper half climbs from i = 1 to n while the lower half descends from i = n to 1, both halves share the exact same three inner loop expressions without modification.

  • Total horizontal width on every line equals 2 * n characters (stars + spaces).
  • Central gap spaces = 2 * (n - i) shrinks by 2 spaces per row in the upper half and grows by 2 in the lower half.
  • Reuse identical inner loops for both wings by reversing only the outer loop direction in the lower half.

2. Dry-Run Trace for n = 4 Across Upper and Lower Halves

Trace ButterflyPattern step by step for n = 4 (total width 8 characters across 8 rows). In the upper half: at i = 1, spaces = 2 * (4 - 1) = 6, printing 1 star, 6 spaces, and 1 star ("* *"). At i = 2, spaces = 2 * 2 = 4, printing "** **". At i = 3, spaces = 2 * 1 = 2, printing "*** ***". At i = 4, spaces = 2 * 0 = 0, so the middle space loop executes zero times and the wings meet seamlessly as "********". Immediately afterward, the lower outer loop begins at i = 4 (repeating "********" to form the symmetric body waist), then steps through i = 3 ("*** ***"), i = 2 ("** **"), and i = 1 ("* *") before terminating cleanly at i = 0.

  • Upper i = 1..4: gap shrinks 6 -> 4 -> 2 -> 0 as wings widen 1 -> 2 -> 3 -> 4.
  • At i = n (4), spaces = 0 joins left and right wings into a solid bar of 8 stars.
  • Lower i = 4..1 mirrors rows 4 through 1 to complete the symmetric lower wings.

3. Symmetrical vs Single-Spine Butterfly Variations

Two visual variants appear in ICSE mock papers and school pre-boards. In the classic double-waist butterfly shown above, the lower outer loop starts at i = n, producing 2 * n rows with two solid middle rows. In the single-waist butterfly (2 * n - 1 rows), simply start the lower outer loop at i = n - 1 so the solid middle row appears once. Also keep character widths consistent if you decide to add breathing room between stars: switching "*" to "* " doubles every star's width, so each gap unit inside the middle loop must also double from " " to " " (printing two spaces spaces times). Finally, placing each sequential inner loop inside its own clean block scope allows reusing the loop index name j safely without variable redeclaration conflicts in BlueJ.

  • Use i = n in the lower loop for 2n rows (double-waist), or i = n - 1 for 2n - 1 rows (single-waist).
  • If printing "* " instead of "*", switch the gap character from " " to " " to keep wings aligned.
  • Sequential for-loops can reuse int j because each loop header confines j to its own block scope.

4. ButterflyPattern.java (BlueJ Ready)

import java.util.Scanner;

public class ButterflyPattern {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter wing size (n): ");
        int n = sc.nextInt();

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

        for (int i = n; i >= 1; i--) {
            for (int j = 1; j <= i; j++) {
                System.out.print("*");
            }
            int spaces = 2 * (n - i);
            for (int j = 1; j <= spaces; j++) {
                System.out.print(" ");
            }
            for (int j = 1; j <= i; j++) {
                System.out.print("*");
            }
            System.out.println();
        }
        sc.close();
    }
}

Verified Console / Dry-Run Output:

Enter wing size (n): 4
*      *
**    **
***  ***
********
********
***  ***
**    **
*      *

5. Variable Description Table (VDT) for ButterflyPattern

Variable NameData TypePurpose in Program
scScannerReads the wing size n entered by the user from System.in
nintStores the half-height (maximum wing width) of the butterfly pattern
iintOuter loop counter tracking the current row in upper and lower halves
jintInner loop counter reused across left-wing, gap, and right-wing loops
spacesintStores the computed central gap width 2 * (n - i) for the current row
🎯 1-on-1 Live Mentorship & Free Study Kit

Master Advanced Java Patterns at 4Achievers Junior

Master complex ICSE Class 10 nested patterns and VDT tables with 4Achievers Junior (Grades 3-12). Book a free 1:1 trial or join our 1:4 Micro-Pods.

💬 WhatsApp Now
🔒 Instant WhatsApp notes + free 60-min 1-on-1 trial session
Confirmed! Our Senior Mentor is sending your study kit & free 1-on-1 demo link on WhatsApp now.

6. Common Mistakes & Top Scorer Tips

  • Avoid Mistake: Using n - i spaces instead of 2 * (n - i), which cuts the central gap in half and collapses the right wing inward.
  • Avoid Mistake: Forgetting the third inner loop for the right wing, printing only an hourglass-like half butterfly.
  • Avoid Mistake: Misaligning space widths when adding a space after stars ("* " requires " " inside the gap loop, not " ").
  • Avoid Mistake: Writing i <= 1 in the lower half countdown loop instead of i >= 1, skipping the entire lower wing.
  • Examiner / Mentor Tip: Write the width formula (left i + gap 2*(n-i) + right i = 2n) as a brief comment or explain it during viva—it immediately shows mastery.
  • Examiner / Mentor Tip: Check the sample output in your question paper to confirm whether the middle solid line appears twice (start at i = n) or once (start at i = n - 1).
  • Examiner / Mentor Tip: Verify that spaces = 2 * (n - i) equals 0 when i == n so the middle row joins cleanly with zero stray spaces.

7. Interactive Concept Check Quiz

Question: For wing size n = 5, what does row 2 (i = 2) of ButterflyPattern print?

8. Frequently Asked Questions

How is the central space formula 2 * (n - i) derived?
Every row of a butterfly with wing size n has total width 2 * n characters. Since the left and right wings together occupy i + i = 2 * i characters, the remaining gap equals 2 * n - 2 * i = 2 * (n - i).
How do I avoid printing the widest middle row twice?
Start the second outer loop at i = n - 1 instead of i = n. That prints the widest full row of 2 * n stars only once at the center, creating a single-waist butterfly of 2n - 1 rows.
Do we need a trailing space loop after the right wing stars?
Yes, wait—never print trailing spaces at the end of a row unless required; the butterfly only needs spaces between the left and right wings, and System.out.println() starts the next line cleanly.

Explore Related Lessons & Free Interactive Tools

Free 1-on-1 Session

Book a Free Demo Class