KnowledgeBoat Logo

Computer Applications

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

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

Java Nested for Loops

1 Like

Answer

Sum = 36

Explanation

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

ijSumsum + (i + j)
1120 + 1 + 1
 252 + 1 + 2
 395 + 1 + 3
21129 + 2 + 1
 21612 + 2 + 2
 32116 + 2 + 3
312521 + 3 + 1
 23025 + 3 + 2
 33630 + 3 + 3
4  Loop terminates

Answered By

2 Likes


Related Questions