ICSE Class 10 Computer Applications Question 54 of 69

Iterative Constructs in Java — Question 9

Back to all questions
9
Question

Question 9

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 last value of i for which the condition i <= 5 will be true is 5. Thus, 5 will be assigned to sum after which the condition will become false and the loop will terminate. Thus, 5 will be printed as output.