Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Displaying a pyramid of number ladder

Tags:

java

I did this below but I didn't get it right,

int i = 1;
       while(i <= 6){
             for(int j = 1;j <= 6-i;j++){
                   System.out.print("  ");
            }
            for(int m = 1; m <= i; m++){
                   System.out.print(m + " ");
            }
            i++;
            System.out.println();
     }

I got this instead :

             1
           1 2
         1 2 3
       1 2 3 4
     1 2 3 4 5 
   1 2 3 4 5 6

But I need guide on how to get this below,

          1
        2 1 2
      3 2 1 2 3
    4 3 2 1 2 3 4
  5 4 3 2 1 2 3 4 5  
like image 832
Rpro Avatar asked Jan 03 '23 14:01

Rpro


2 Answers

while(i <= 6){
    for(int j = 1; j <= 6 - i; j++){
        System.out.print("  ");
    }
    for(int m = i-1; m > 1; m--){
        System.out.print(m + " ");
    }
    for(int m = 1; m < i; m++){
        System.out.print(m + " ");
    }

    i++;
    System.out.println();
}

This should work for you, i just added / edited this part:

    for(int m = i-1; m > 1; m--){
        System.out.print(m + " ");
    }
    for(int m = 1; m < i; m++){
        System.out.print(m + " ");
    }

To let it count down again, and let it count up afterwards

like image 104
Marvin Fischer Avatar answered Jan 05 '23 18:01

Marvin Fischer


This should do the trick, but it's important to understand what is going on:

public class Main {

    public static void main(String[] args) {

        for (int i = 0; i <= 6; i++) {
            printRow(6, i);
        }
    }

    public static void printRow(int highestValue, int rowValue) {

        for (int i = 0; i < (highestValue - rowValue); i++) {
            System.out.print("  ");
        }

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

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

        System.out.println();
    }
}

The first loop pads the left side of the pyramid, as you have already done. The second loop counts down from the value of the row to 1, which is the center of the pyramid. The third loop counts back up from 2 to the value of the row. Note that for the first row, 2 will not be printed, because i = 2 is greater than rowValue, which is 1, so the loop is skipped.

Running this results in the following:

          1 
        2 1 2 
      3 2 1 2 3 
    4 3 2 1 2 3 4 
  5 4 3 2 1 2 3 4 5 
6 5 4 3 2 1 2 3 4 5 6 

Note that a row starting with 6 is printed since I used the bounds you provided. If this is not what should be done (from your example output), I will leave that up to you on how to fix this. Pay attention to the name of the arguments in the printRow method to see why there is an extra row printed.

like image 34
Justin Albano Avatar answered Jan 05 '23 18:01

Justin Albano