简体   繁体   中英

Unable to understand this particular program

I'm finding it difficult to understand what is happening in this program code. Please help. Thanks

public class ArrayTriangle
{ 
    public static void main( String[] args )
    {
        int[][] triangle = new int[10][];
        for ( int j = 0; j<triangle.length ; j++ )

            triangle[ j ] = new int[ j + 1 ];         /*Please explain me this line*/
    }
}   

It is creating an array of array, like this

triangle[ 0 ] = new int[ 1 ];
triangle[ 1 ] = new int[ 2 ];
triangle[ 2 ] = new int[ 3 ];
...

You are creating a 2-D array

triangle[0] = new int[1];
triangle[1] = new int[2];
triangle[2] = new int[3];

You can will will have a 2-D array with 0th element having size of 1, 1st with 2 and so on.

This is the output if you print the array which is clearly a triangle.

for (int j = 0; j < triangle.length; j++){
        for(int k = 0; k < triangle[j].length ; k++){
            System.out.print(triangle[j][k]);
        }

        System.out.println("");
    }

Use the above snippet to see print your triangle.

[[0], [0, 0], [0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM