Home > Software engineering >  Displaying a pyramid
Displaying a pyramid

Time:09-28

I have this task to display a pyramid as follows: enter image description here

I wrote the code but unfortunately, the digits are displayed with spaces and order.

public class DisplayPyramid {
//main method declaration. Program entry point which begins its execution
public static void main(String[] args) {
    //Create a Scanner object
    Scanner input = new Scanner(System.in);

    //Prompt the user to enter an integer (number of lines)
    System.out.print("Enter the number of lines: ");
    int numbers = input.nextInt(); //Read value from keyboard and assign it to numberOfLines

    String padding = "  ";

    //Display pyramid

    //for loop to produce each row
    for (int rows = 0; rows < numbers ; rows  ) {

        for (int k = numbers - rows; k >= 1; k--){
            System.out.print(k   "  ");
        }

        for (int l = 2; l <= numbers - rows; l  ){
            System.out.print("  "   l);
        }


        //Advance to the next line at the end of each rows
        System.out.print("\n");
    }
} }

And this is my output: enter image description here

Can you help me figure out what is wrong with code ? Anyone's help will be much appreciated.

CodePudding user response:

Consider the 1st pass of the outer loop which produces
enter image description here

If we color hint your code, which the first inner loop in red, the second inner loop in green
enter image description here
This will be their corresponding output for each pass
enter image description here
The last pass of the red loop print "1 " and the first pass of green loop print " 2". They combine and become "1 2", which has 2 spaces in between.

The solution as Osama A.R point out, just reverse the printing order of number and space for the green loop and make if follow the red loop pattern. That will make the sequence neat.

CodePudding user response:

Your second for loop prints the spaces first and then the number, however, the spaces have already been added by the first for loop, so just update the second for loop to print the spaces after printing the number.

E.g. your second loop should be like this:

for (int l = 2; l <= numbers - rows; l  ){
    System.out.print(l   "  ");
}
  • Related