Java Programming - Language Fundamentals - Discussion

Discussion Forum : Language Fundamentals - Finding the output (Q.No. 7)
7.
In the given program, how many lines of output will be produced?
public class Test 
{
    public static void main(String [] args) 
    {
    int [] [] [] x = new int [3] [] [];
    int i, j;
    x[0] = new int[4][];
    x[1] = new int[2][];
    x[2] = new int[5][];
    for (i = 0; i < x.length; i++)
    {
        for (j = 0; j < x[i].length; j++) 
        {
            x[i][j] = new int [i + j + 1];
            System.out.println("size = " + x[i][j].length);
        }
    }
    }
}
7
9
11
13
Compilation fails
Answer: Option
Explanation:

The loops use the array sizes (length).

It produces 11 lines of output as given below.

D:\Java>javac Test.java

D:\Java>java Test
size = 1
size = 2
size = 3
size = 4
size = 2
size = 3
size = 3
size = 4
size = 5
size = 6
size = 7

Therefore, 11 is the answer.

Discussion:
17 comments Page 1 of 2.

Chidu said:   7 years ago
0th iteration->0 1 2 3;
1st iteration->0 1;
2ns iteration->0 1 2 3 4.
count total number in the right side,
So ans is 11.
(1)

Gopal said:   1 decade ago
When i=0 then x[0].length=4 (given in the program that x[0] = new int[4][]).
Here j loop repeats 4 times.

When i=1 then x[1].length=2 (given in the program that x[1] = new int[2][]).
Here j loop repeats 2 times.

When i=2 then x[2].length=5 (given in the program that x[2] = new int[5][]).
Here j loop repeats 5 times.

Totally it executes 11 lines.
(1)

HARSHAD said:   7 years ago
x[0] = new int[4][];
x[1] = new int[2][];
x[2] = new int[5][];
4+2+5=11.
(1)

Hye Jung said:   8 years ago
Why is the second for loop executed first?

Srrivatsan Sekar said:   4 years ago
Yes, @abhijit.

Java allows 3D arrays. Because in java we have 1D and multi D arrays. In the case of multi-D arrays, we can have 2D and 3D arrays.

Tanu said:   5 years ago
I guess the answer should be 9. It could have been 11 if the condition for the loops would be i/j<=x. Length().

Vicky said:   7 years ago
How the size of array becomes 4?

Logaa said:   7 years ago
Can anyone please explain that nested for loop operation in detail? please.

Rahul said:   8 years ago
Well explained @Sri.

@All.
Please check Sri's explanation to understand the answer.

MSH said:   8 years ago
@Maheshthakuri and @Sri.

Well said, Thanks for explaining it.


Post your comments here:

Your comments will be displayed after verification.