Computer Applications

What will be the value of sum after each of the following nested loops is executed?

int sum = 0;
for (int i = 0; i <= 10; i++)
    for (int j = 0; j <= 10; j++) 
        sum += i;

Java Nested for Loops

3 Likes

Answer

Sum = 605

Explanation

The outer loop executes 11 times. For each iteration of outer loop, the inner loop executes 11 times. For every value of j, i is added to sum 11 times. Consider the following table for the value of sum with each value of i and j.

ijSumRemarks
00 - 1000 is added to sum 11 times
10 - 10111 is added to sum 11 times
⇒ 0 + 11 = 11
20 - 10332 is added to sum 11 times
⇒ 11 + 22 = 33
30 - 10663 is added to sum 11 times
⇒ 33 + 33 = 66
40 - 101104 is added to sum 11 times
⇒ 66 + 44 = 110
50 - 101655 is added to sum 11 times
⇒ 110 + 55 = 165
60 - 102316 is added to sum 11 times
⇒ 165 + 66 = 231
70 - 103087 is added to sum 11 times
⇒ 231 + 77 = 308
80 - 103968 is added to sum 11 times
⇒ 308 + 88 = 396
90 - 104959 is added to sum 11 times
⇒ 396 + 99 = 495
100 - 1060510 is added to sum 11 times
⇒ 495 + 110 = 605
11  Loop terminates

Answered By

1 Like


Related Questions