Nishant Singh
Nishant Singh

Reputation: 9

Having problem in printing butterfly pattern with stars in java

public static void butterFly(int n){
    //Outer loop
    for(int i = 1; i <= n; i++){
        // star - i
        for(int j = 1; j <= i; j++){
            System.out.print("* ");
        }
        //Spaces - 2 * (n - i)
        for(int j = 1; j <= 2*(n-i); j++){
            System.out.print(" ");
        }
        //Stars - i
        for(int j = 1; j <= i; j++){
            System.out.print("* ");
        }
        System.out.println();
    }
    // 2nd half
    //Outer loop
    for(int i = n; i >= 1; i--){
        // star - i
        for(int j = 1; j <= i; j++){
            System.out.print("* ");
        }
        //Spaces - 2 * (n - i)
        for(int j = 1; j <= 2*(n-i); j++){
            System.out.print(" ");
        }
        //Stars - i
        for(int j = 1; j <= i; j++){
            System.out.print("* ");
        }
        System.out.println();
    }
*         * 
* *       * *
* * *     * * *
* * * *   * * * *
* * * * * * * * * *
* * * * * * * * * *
* * * *   * * * *
* * *     * * *
* *       * *
*         *

I was expecting this

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

I have breaked my code into 2 parts 1st half of butterfly and second half of butterfly . For print stars i have taken the value j =i where i is less then equals to n which is user input. for printing spaces i have taken the j <= 2*(n-i). and for the 2nd part i just reversed the outer loop.

Upvotes: 0

Views: 609

Answers (1)

cha_lar
cha_lar

Reputation: 134

You should remove spaces after *, i.e., System.out.print("* "); should be System.out.print("*");

Also, if you do not want the middle row to be duplicated, start the second half from n - 1, not n.

    //Outer loop
    for(int i = 1; i <= n; i++){
        // star - i
        for(int j = 1; j <= i; j++){
            System.out.print("*");
        }
        //Spaces - 2 * (n - i)
        for(int j = 1; j <= 2*(n-i); j++){
            System.out.print(" ");
        }
        //Stars - i
        for(int j = 1; j <= i; j++){
            System.out.print("*");
        }
        System.out.println();
    }
    // 2nd half
    //Outer loop
    for(int i = n - 1; i >= 1; i--){
        // star - i
        for(int j = 1; j <= i; j++){
            System.out.print("*");
        }
        //Spaces - 2 * (n - i)
        for(int j = 1; j <= 2*(n-i); j++){
            System.out.print(" ");
        }
        //Stars - i
        for(int j = 1; j <= i; j++){
            System.out.print("*");
        }
        System.out.println();
    }

Upvotes: 1

Related Questions