Search code examples
javafor-looppyramid

java pyramid with multiple of 2 not working


I am suppose to create a pyramid and multiply each number by two until it reach the middle then divide by two such as shown in example below.

the right pyramid

However after writing my code I am unable to have the numbers double (i*2) then once it reaches the center it divides by two until the it becomes 1

My output:

my code that doesn't come out right

 package question5;

 public class Pyramid {

 public static void main(String[] args) {
    int x = 5;
    int rowCount = 1;

    System.out.println("Here Is Your Pyramid");

    //Implementing the logic

    for (int i = x; i > 0; i--)
    {
        //Printing i*2 spaces at the beginning of each row

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

        //Printing j value where j value will be from 1 to rowCount

        for (int j = 1; j <= rowCount; j++)             
        {
        System.out.print(j+" ");
        }

        //Printing j value where j value will be from rowCount-1 to 1

        for (int j = rowCount-1; j >= 1; j--)
        {                    
        System.out.print(j+" ");             
        }                          

        System.out.println();

        //Incrementing the rowCount

        rowCount++;
    }
}
}

this is the weird output of it


Solution

  • This is working... You can use math.pow method.

    public class test {
    
         public static void main(String[] args) {
            int x = 5;
            int rowCount = 1;
    
            System.out.println("Here Is Your Pyramid");
            //Implementing the logic
    
            for (int i = x; i > 0; i--)
            {
                //Printing i*2 spaces at the beginning of each row
                for (int j = 1; j <= i*2; j++)
                {
                    System.out.print(" ");
                }
    
                //Printing j value where j value will be from 1 to rowCount
    
                for (int j = 0; j <= rowCount-1; j++)             
                {
                System.out.printf("%2d", (int)Math.pow(2, j));  
                }
    
                //Printing j value where j value will be from rowCount-1 to 1
    
                for (int j = rowCount-1; j >= 1; j--)
                {                    
                System.out.printf("%2d", (int)Math.pow(2, j-1));
                }                          
    
                System.out.println();
    
                //Incrementing the rowCount
    
                rowCount++;
    
            }
        }
        }