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;
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
.
i | j | Sum | Remarks |
---|---|---|---|
0 | 0 - 10 | 0 | 0 is added to sum 11 times |
1 | 0 - 10 | 11 | 1 is added to sum 11 times ⇒ 0 + 11 = 11 |
2 | 0 - 10 | 33 | 2 is added to sum 11 times ⇒ 11 + 22 = 33 |
3 | 0 - 10 | 66 | 3 is added to sum 11 times ⇒ 33 + 33 = 66 |
4 | 0 - 10 | 110 | 4 is added to sum 11 times ⇒ 66 + 44 = 110 |
5 | 0 - 10 | 165 | 5 is added to sum 11 times ⇒ 110 + 55 = 165 |
6 | 0 - 10 | 231 | 6 is added to sum 11 times ⇒ 165 + 66 = 231 |
7 | 0 - 10 | 308 | 7 is added to sum 11 times ⇒ 231 + 77 = 308 |
8 | 0 - 10 | 396 | 8 is added to sum 11 times ⇒ 308 + 88 = 396 |
9 | 0 - 10 | 495 | 9 is added to sum 11 times ⇒ 396 + 99 = 495 |
10 | 0 - 10 | 605 | 10 is added to sum 11 times ⇒ 495 + 110 = 605 |
11 | Loop terminates |
Related Questions
Distinguish between the following:
break statement and labelled break statement
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);
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
1Distinguish between the following:
continue statement and labelled continue statement