ICSE Class 10 Computer Applications Question 55 of 69

Iterative Constructs in Java — Question 10

Back to all questions
10
Question

Question 10

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

Infinite loop

Reason — The initial value of i is 10 and the test condition is i > 5 is true. In the next iteration, the value of i is incremented by 1 and again the condition is true. Thus, the value of i will keep on incrementing and the test expression will remain true, creating an infinite loop.