Home > database >  java inverted pyramid of numbers?
java inverted pyramid of numbers?

Time:01-07

I was asked to create a java program that will display an inverted pyramid of numbers (1 to 9 only). with user input of how many number of rows.

I don't know how to loop and limit the numbers to 9 and change it to the right side.

My code is:

    public static void main(String[] args) {
        Scanner sc = new Scanner (System.in);
        
        System.out.print("Enter height:\t");
        int height = sc.nextInt();
        
        for (int row = height; row >= 1; row--) {
            for (int col = 1; col <= row; col  ) {
                System.out.print("");
            }
            for (int k = 1; k <= row; k  ) {
                System.out.print(row   "");
            
            }
            System.out.println();
        }
        
        
    }
}

the output is:

Enter height:   12
121212121212121212121212
1111111111111111111111
10101010101010101010
999999999
88888888
7777777
666666
55555
4444
333
22
1

the output should be:

Enter height:  12
    111111111111
     22222222222
      3333333333
       444444444
        55555555
         6666666
          777777
           88888
            9999
             111
              22
               3

OR:

Enter height:  20
11111111111111111111
 2222222222222222222
  333333333333333333
   44444444444444444
    5555555555555555
     666666666666666
      77777777777777
       8888888888888
        999999999999
         11111111111
          2222222222
           333333333
            44444444
             5555555
              666666
               77777
                8888
                 999
                  11
                   2

CodePudding user response:

Your main loop is running from height to 0 which is causing the numbers you print to be from height to 1 where as output expects it in ascending order.

output further expects that any value of height greater than 9 be treated as single digit increments again so after 9 comes 1 again instead of 10.

you have the write thought by appending space but to append space in java you actually have to add space in between the two ""

Example:

System.out.print(" ").

Fixing all above issues code snippet should look something like this :

    public static void main(String[] args) {
        Scanner sc = new Scanner (System.in);
        
        System.out.print("Enter height:\t");
        int height = sc.nextInt();
        
        for (int row = 1; row <=height; row  ) {
            for (int space = 1; space < row; space   ) {
                System.out.print(" ");
            }
            for (int val = row ; val <= height; val  ) {
                if(row>9){
                    System.out.print(row 1);
                }
                else{
                     System.out.print(row);
                }
            }
            System.out.println();           
        }
    }
  •  Tags:  
  • Related