Home > OS >  For loop for increasing pyramid pattern
For loop for increasing pyramid pattern

Time:12-23

I am trying to figure out how to increment a pyramid based on input from the user.\ If a user enters the number 3, my program will print a pyramid of height 3, three times.\ What I would like it to do instead, is to print 3 pyramids, but the first pyramid should have a height of 1, and the second a height of 2, and the third a height of 3.

Here is my code:

public static void main(String[] args) {

    Scanner scanner = new Scanner(System.in);

    int n = scanner.nextInt();

    for (int l = 0; l < n; l  ) {

        System.out.println("Pyramid "   n);

        for (int i = 1; i <= n; i  ) {

            for (int j = 0; j < n - i; j  ) {
                System.out.print(".");
            }

            for (int j = 0; j < i; j  ) {
                System.out.print("#");
            }

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

            for (int k = 0; k < n - i; k  ) {
                System.out.print(".");
            }
            System.out.println();
        }
    }

CodePudding user response:

You use l to keep track of the number of pyramid you're working on, so you could just use it in the loop instead of n. Note that l starts with 0, not 1, so you may want to amend the loop accordingly and run from 1 to n, not from 0 to n-1

for (int l = 1; l <= n; l  ) { // Note the loop starts at 1

    System.out.println("Pyramid "   l);

    for (int i = 1; i <= l; i  ) { // Note the usage of l instead on n

        for (int j = 0; j < l - i; j  ) {
            System.out.print(".");
        }

        for (int j = 0; j < i; j  ) {
            System.out.print("#");
        }

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

        for (int k = 0; k < l - i; k  ) { // Note the usage of l instead on n
            System.out.print(".");
        }
        System.out.println();
    }
}

CodePudding user response:

All you have to change is this part of code

System.out.println("Pyramid "   (l 1));

        for (int i = 1; i <= l 1; i  ) {
  •  Tags:  
  • java
  • Related