ICSE Class 10 Computer Applications
Question 16 of 22
Nested for loops — Question 16
Back to all questions 16
Question Question 5(ii)
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);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.
| i | j | Sum | sum + (i + j) |
|---|---|---|---|
| 1 | 1 | 2 | 0 + 1 + 1 |
| 2 | 5 | 2 + 1 + 2 | |
| 3 | 9 | 5 + 1 + 3 | |
| 2 | 1 | 12 | 9 + 2 + 1 |
| 2 | 16 | 12 + 2 + 2 | |
| 3 | 21 | 16 + 2 + 3 | |
| 3 | 1 | 25 | 21 + 3 + 1 |
| 2 | 30 | 25 + 3 + 2 | |
| 3 | 36 | 30 + 3 + 3 | |
| 4 | Loop terminates |