class NestedFor { public static void main(String s[]) { for(int i = 2; i <= 5; i++ ) { for(int j = i; j <= 5; j++ ) { System.out.println("i = " + i + " j = " + j); } }
} }
i = 2 j = 1 i = 2 j = 2 i = 2 j = 3 i = 2 j = 4 i = 2 j = 5 i = 3 j = 1 i = 3 j = 2 i = 3 j = 3 i = 3 j = 4 i = 3 j = 5 i = 4 j = 1 i = 4 j = 2 i = 4 j = 3 i = 4 j = 4 i = 4 j = 5 i = 5 j = 1 i = 5 j = 2 i = 5 j = 3 i = 5 j = 4 i = 5 j = 5
i = 2 j = 2 i = 2 j = 3 i = 2 j = 4 i = 2 j = 5 i = 3 j = 3 i = 3 j = 4 i = 3 j = 5 i = 4 j = 4 i = 4 j = 5 i = 5 j = 5
Compilation error since variable i can not be used in the inner for loop.
i = 2 j = 1 i = 2 j = 2 i = 2 j = 3 i = 2 j = 4 i = 2 j = 5
Correct Answer : B
Execution of program starts from main. Inside main are two nested for loops.
First for loop is as follows:
Initialization : i = 2
Terminating condition : i <= 5
Increment Value : 1 (i++)
Inner for loop is as follows:
Initialization : j = i
Terminating condition : j <= 5
Increment Value : 1 (j++)
Total number Of Iterations : 4 + 3 + 2 + 1 = 10
Iteration 1 :
Display statement prints i = 2j = 2 j is incremented to 3.
Iteration 2 :
Display statement prints i = 2j = 3 j is incremented to 4.
Iteration 3 :
Display statement prints i = 2j = 4 j is incremented to 5.
Iteration 4 :
Display statement prints i = 2j = 5 j is incremented to 5 and inner loop terminates. Now i increments and becomes 3. Now inner loop again starts.
Similarly the other iterations.
When i, j becomes 5 loops terminate.