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);
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
.
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 |
Related Questions
Distinguish between the following:
break statement and labelled break statement
Write a program to generate a triangle or an inverted triangle till n terms based upon the user's choice.
Example 1:
Input: Type 1 for a triangle and
Type 2 for an inverted triangle
Enter your choice 1
Enter the number of terms 5
Sample Output:
1
2 2
3 3 3
4 4 4 4
5 5 5 5 5Example 2:
Input: Type 1 for a triangle and
Type 2 for an inverted triangle
Enter your choice 2
Enter the number of terms 6
Sample Output:
6 6 6 6 6 6
5 5 5 5 5
4 4 4 4
3 3 3
2 2
1What 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;
Distinguish between the following:
continue statement and labelled continue statement