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);
}
  1. 15
  2. 21
  3. 5
  4. 0
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.

Get the Bright Tutorials app Stuck on a question? Ask Bright Buddy — your AI tutor — for step-by-step help in the app.