Computer Applications
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
Java Iterative Stmts
12 Likes
Answer
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.
Answered By
7 Likes
Related Questions
Which of the following is not a jump statement in Java?
- return
- jump
- break
- continue
How many times will the following code print "Hello"?
for (int i = 1; i <= 5; i++); { System.out.println("Hello"); }- 0
- 1
- 5
- 4
How many times will the following loop execute?
public static void main(String args[]) { int sum = 0; for (int i = 10; i > 5; i++) { sum += i; } System.out.println(sum); }- 5
- 0
- 15
- Infinite loop
How many times will the following loop execute?
public static void main(String args[]) { int i = 1; while (i < 10) if (i++ % 2 == 0) System.out.println(i); }- 4
- 5
- 0
- 10