Explain creating a pyramid in Java

后端 未结 7 1323
独厮守ぢ
独厮守ぢ 2020-12-18 17:04

I am in a beginner java programming class and currently reviewing loops. If there is one thing I just do not understand, it\'s pyramids. I have researched the book exercis

7条回答
  •  长情又很酷
    2020-12-18 17:41

    You can also try this if it helps :)

         *
        ***
       *****
      *******
     *********
    

    OUTPUT:

    ROW (1) * --> COLUMN
    |   (2) *
    |   (3) ***
    |   (4) *****
    v   (5) *******
    

    CODE LOGIC: First divide the pyramid into 3 triangle.

    ####$
    ###$$@
    ##$$$@@
    #$$$$@@@
    $$$$$@@@@
    

    1> First triangle (White spaces represented by #)

    ####
    ###
    ##
    #
    

    2> Second triangle (represented by $)

    $
    $$ 
    $$$
    $$$$
    $$$$$
    

    3> Third triangle (represented by @)

    #
    @
    @@
    @@@
    @@@@
    

    Together it will make a pyramid structure

    CODE:

    pyramid() {
        for (int i = 1; i <= 5; i++) { // loop row
            for (int k = 1; k <= 5 - i; k++) { // 1st triangle (printing space)
                System.out.print(" ");
            }
            for (int j = 1; j <= i; j++) { // 2nd triangle
                System.out.print("*");
            }
            for (int l = 1; l <= i - 1; l++) { //3rd triangle
                if (i == 1) {
                    break;
                }
                System.out.print("*");
            }
    
            System.out.println();
        }
    }
    

提交回复
热议问题