Explain creating a pyramid in Java

后端 未结 7 1266
独厮守ぢ
独厮守ぢ 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();
        }
    }
    
    0 讨论(0)
  • 2020-12-18 17:45

    It begins by declaring x to be 7. Then a for loop starts. This loop is going to start off by saying a variable i to be 1. Its contents (the code block starting with { and ending with the corresponding }) will be run as long as the for loop's second part (i <= x) evaluates to true. At the end of such an execution, the last part is going to be performed: i++, which increments variable i by one.

    So what happens is:

    • i set to 1
    • i <= x ?
      • Yes! 1 is smaller than or equal to 7. Do the stuff in the code block.
    • i goes from 1 to 2
    • i <= x ?
      • Yes! 2 is smaller than or equal to 7. Do the stuff in the code block.
    • ... several iterations ...
    • i goes from 7 to 8
      • i <= x ?
      • No! 8 is not smaller than or equal to 7. For loop ends.

    That's the outer loop. Now, we'll need to figure out what happens in one such iteration of the for loop. So let's look at that code block which gets executed 7 times.

    for (int j = 1; j <= x - i; j++)  
    System.out.print("   "); 
    
    for (int k = i; k >= 1; k--)  
    System.out.print((k >=10) ?+ k : "  " + k);  
    
    for (int k = 2; k <=i; k++)  
    System.out.print((k>= 10) ?+ k : "  " + k);  
    System.out.println();  
    

    There's three logical parts here, conveniently separated by a blank line. What may be confusing here is that these three parts are in the outer for loop's code block, but are not nested any deeper. Take a look at this first one:

    for (int j = 1; j <= x - i; j++)  
    System.out.print("   "); 
    

    This time there's no { or } to delimit what is part of the for's code block. By default, this means only the next statement is part of it, or in this case System.out.print(" ");.

    What happens in that bit of code? Well, it's another for, this time starting from 1 and running until x - i. x is still 7, but i depends on which iteration of the outer for loop we're in. First time round it'll be 1. That will correspond to the first row you see in the output. Second time round it'll be 2. That will correspond to the second row of the output.

    So suppose this is the first iteration of the outer for loop. x - i is then really 7 - 1, which is 6. We let some variable j go from 1 to 6. Each of these 6 times, we're printing out 3 space characters.

    After that, we arrive at the second part:

    for (int k = i; k >= 1; k--)  
    System.out.print((k >=10) ?+ k : "  " + k); 
    

    Another for loop, but with a twist. This one uses a variable k that starts at i and then counts down to 1, as indicated by the k--. For each of these iterations, it prints out more stuff to the output. The content of the print statement is a bit more complex this time. It uses a ternary operator. That first bit (k >=10) is going to be evaluated. If it is true, it'll return the bit before :, otherwise it'll return the bit after :. In this case, it means that if k is larger than or equal to 10, it'll print out just k's value. Otherwise, it'll print out two spaces plus k's value.

    After this, the last bit should be easy to figure out. Notice that after the for loop and its single statement, there's a System.out.println(); All this does is print out a line break, making the output go to the next line.

    That marks the end of one iteration of the outer for loop. As long as i is nog larger than x (7 in our case), another iteration will start and those three parts are gonna run. Since those three inner for loops are dependent on i, they're always gonna run a different amount of times.

    Mentally do the following: go through at least three iterations of the outer for loop. That means, think of i being 1 and mentally execute the stuf between { and }. Then think of i being 2 and do the same. Do it again for 3 and by now it should start to become clear.

    Good luck!

    0 讨论(0)
  • 2020-12-18 17:47

    We can make pyramid with one for loop as well, making it performance efficient code in terms of execution time.

    Here is the code which prints pyramid of asterisk.

    public class PyramidPrinting {
    
        public static void main(String[] args) {
            int h = 5;
            int i,j;
            char[] arr = new char[2*h-1];
    
            for(i=h-1,j=h-1; i>=0 && j<=2*h-1; i--,j++){
                arr[i]='*';
                arr[j]='*';
                System.out.println(arr);
            }
        }
    }
    

    output:

        *
       ***
      *****
     *******
    *********
    
    0 讨论(0)
  • 2020-12-18 17:50
    public static void main(String[] args) {
    
        // levels in the pyramid
        int x = 5;
    
        for (int i = 1; i <= x; i++) {
            // for spacing
            for (int j = 1; j <= x - i; j++){                System.out.print("   ");            }           // left half of the pyramid             for (int k = i; k >= 1; k--){
                System.out.print((k >= 10) ? +k : "  " + k);
            }
            // corresponding right half of the pyramid
            for (int k = 2; k <= i; k++) {               System.out.print((k >= 10) ? +k : "  " + k);
            }
            // next line
            System.out.println();
        }
    }
    

    Credit: http://www.skilledmonster.com/2013/10/28/java-pyramid-example-pattern-11/

    0 讨论(0)
  • 2020-12-18 17:56

    well I made a similar program with no issues and just imagination... the code is so clear :D

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        int i,j,k, n = Integer.parseInt(jTextField1.getText());
        for(i=1;i<=n;i++) // normal loop
        { 
            for(j=1; j<=(n-i);j++)
            {
                System.out.print(" "); // loop for spaces
            }
            for(k=1;k<=i;k++) // loop for printing numbers
            {
                System.out.print(k+" ");
            }
            System.out.println();
        }    // TODO add your handling code here:
    }
    
    0 讨论(0)
  • 2020-12-18 18:02

    There are 7 rows in the pyramid, so the first for loop is looping over the rows, the second for loop is printing a bunch of spaces so that the triangle doesnt appear as:

    1
    2 1 2
    3 2 1 2 3
    

    The third for loop (with k), has a conditional operator which works like this:

    boolean-expression ? result-if-true : result-if-false
    

    So it either adds the number k to the string, or adds a space and then the number k to the string.

    Fourth loop does a similar thing.

    0 讨论(0)
提交回复
热议问题