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);
}
  1. 15
  2. 21
  3. 5
  4. 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 IterationsValue of iValue of sumTest Condition
1st11True
2nd22True
3rd33True
4th44True
5th55False

Thus, for loop terminates when the value of sum is 5. Hence the output is 5.

Answered By

7 Likes


Related Questions