Explain creating a pyramid in Java

2020-02-11 12:09发布

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 exercises online and found the solutions to the pyramid examples, but even seeing the code, I still don't understand and couldn't recreate the answers if my life depended on it.

Below is a pyramid example and the code that creates it. If someone could walk through the code and give me a line by line 'for dummies' explanation of what is going on then maybe I'll finally understand.

Thanks in advance for you help!

ex. create the following pyramid:

            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    
7 6 5 4 3 2 1 2 3 4 5 6 7
class Pyramid {

    public static void main(String[] args) {

        int x = 7;

        for (int i = 1; i <= x; i++) {

            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();
        }  
    }
}

7条回答
看我几分像从前
2楼-- · 2020-02-11 12:15

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();
    }
}
查看更多
We Are One
3楼-- · 2020-02-11 12:15

Let's First understand For loop:

For Loop:

It is structured around a finite set of repetitions of code. So if you have a particular block of code that you want to have run over and over again a specific number of times the For Loop is helpful.

Syntax:

for(initilization; conditional expression; increment expression)
{
    //repetition code here
}

eg:

int x = 7;
for (int i = 1; i <= x; i++){
    // statements
}

In this "int i=1" is an initialization part, the loop will iterate till condition is true that is (I <=x) replace the value of I and x(1<=7).

After this statement inside the loop body will be executed and in the end "i++" that is the value of "I" will be incremented (I will become 2).

This process will repeat every time till the condition (I <= x) is true.


Now lets understand how pattern are form:

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

As we can see there are two things that need to be considered first the number of rows and second the number of columns:

We use two loops to construct such structures, first outer loop for number of rows and second inner loop for number of columns.

CODE LOGIC: First divide the pyramid into 3 triangle.

enter image description here

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

1> First triangle (White spaces represented by #)

####
###
##
#

2> Second triangle (represented by $)

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

3> Third triangle (represented by @)

#
@
@@
@@@
@@@@

Together it will make a pyramid structure


Lets begin :

Now lets breakdown our pattern problem:

enter image description here

######1
#####212
####32123
###4321234
##543212345
#65432123456
7654321234567

We will break this into 3 triangles and every triangle will have its own loop inside the main loop for the number of rows. As we can see a number of rows required for our pattern are 7 so we will make the first loop to repeat till 7 rows are achieved.

main loop (for rows):

int x = 7;
for (int i = 1; i <= x; i++) { // main loop for number of rows

    // other 3 loops will come insidethe mail loop

}   

First inner loop: As we have seen in pattern logic that the first triangle will consist of white spaces or blank.

                output eg: (representing white spaces with #)



                            ######          
                            #####   
                            ####    
                            ###
                            ##
                            #       


for (int j = 1; j <= x - i; j++)    // j represent a column number 
   System.out.print("   ");  
// This will create blank spaces till the condition is true.




**condition explained:** j <= x - i

Value of "i" is "1" as this is the first time the main loop is running and ever since the value of "i" has not changed.

 **replace values:** 

when j = 1 : 1 <= 7-1 (will print) ######

//first iteration of main loop and inner loop.

after this control will go to the next loop i.e second inner loop:

j = 2 : 2 <= 7-1 (will print) #####

// on second iteration of main loop and inner loop.

after this control will go to the next loop i.e second inner loop:

j = 3 : 3 <= 7-1 (will print) ####

// on third iteration of main loop and inner loop.

after this control will go to the next loop i.e second inner loop:

j = 4 : 4 <= 7-1 (will print) ###

//on fourth iteration of main loop and inner loop.

after this control will go to the next loop i.e second inner loop:

j = 5 : 5 <= 7-1 (will print) ##
// on fifth iteration of main loop and inner loop.

after this control will go to the next loop i.e second inner loop:

j = 6 : 6 <= 7-1 (will print) #

//on sixth iteration of main loop and inner loop.

after this control will go to the next loop i.e second inner loop:

j = 7 : 7 <= 7-1 //end of first inner loop as (7<=6 is not true)


Second inner loop :

for (int k = i; k >= 1; k--) //second triangle
                System.out.print((k >= 10) ?+ k : "  " + k);  // ternary operator is used to check the printing logic

NOTE:

ternary operator syntax: result = testCondition ? value1 : value2

// if testcondition is true then result will get value1 else value 2

***DIY: (Take a paper pen)***
    Implement for loop logic and replace variables with values: 

First iteration: K=i (we know i=1) so k=1; k>=1 (Replacing variables we get 1>=1 which is true); execute statements.

Statement: System.out.print((k >= 10) ?+ k : " " + k); or if(1>=10)? then print value of "k" (that is 1)

else print vlaue of "k" with some spaces ahead k (in order to make the pyramid look even spaced)

NOTE: if you are getting confused with ternary operator then don't use it, you can simply wirte.

System.out.print("  " + k); // will give same output

after this control will go to the next loop i.e third inner loop:

                *Second innerloop is used to print this portion:* 


                             1
                            21
                           321
                          4321
                         54321      
                        654321
                       7654321      

Third inner loop: This loop is used to print the third triangle.

                            2
                            23
                            234
                            2345
                            23456
                            234567



for (int k = 2; k <=i; k++) //  loop column  
                System.out.print((k >= 10) ?+ k : "  " + k); 
                            or
                System.out.print("  " + k)

lets see full code:

    int x = 7;   

    for (int i = 1; i <= x; i++) {              // loop row

        for (int j = 1; j <= x - i; j++)        // loop column (Triangle one)
            System.out.print("   ");

        for (int k = i; k >= 1; k--)            // loop column (Triangle two)
            System.out.print(  "  " + k);

        for (int k = 2; k <=i; k++)             // loop column (Triangle three)
            System.out.print( "  " + k);

        System.out.println();                   // used to go on new line (new row)
    }  
查看更多
唯我独甜
4楼-- · 2020-02-11 12:26

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:
}
查看更多
爷、活的狠高调
5楼-- · 2020-02-11 12:27

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!

查看更多
时光不老,我们不散
6楼-- · 2020-02-11 12:33

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:

    *
   ***
  *****
 *******
*********
查看更多
ゆ 、 Hurt°
7楼-- · 2020-02-11 12:39

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.

查看更多
登录 后发表回答