ICSE Class 9 Computer Applications
Question 28 of 29
Iterative Constructs in Java — Question 6
Back to all questions 6
Question Question 6
What will be the output of the following code?
public static void main(String args[])
{
int sum = 0;
for (int i= 1; i <= 5; i++)
{
sum = i;
}
System.out.println(sum);
}- 15
- 21
- 5
- 0
5
Reason — The values of i and sum as per the execution of the for loop are as follows:
| No. of Iterations | Value of i | Value of sum | Test Condition |
|---|---|---|---|
| 1st | 1 | 1 | True |
| 2nd | 2 | 2 | True |
| 3rd | 3 | 3 | True |
| 4th | 4 | 4 | True |
| 5th | 5 | 5 | False |
Thus, for loop terminates when the value of sum is 5. Hence the output is 5.