KnowledgeBoat Logo
|

Computer Applications

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

Java Iterative Stmts

14 Likes

Answer

Loop executes 9 times

Reason — There is a misprint in the book. The loop executes 9 times. Value of i is printed 4 times inside the loop. The condition if (i++ % 2 == 0) will be false when i is odd and true when i is even. Value of i will be incremented after if check is performed due to post increment opertor i++. Execution of the loop is summarized in the table below:

Iterationsii++ % 2 == 0OutputRemarks
1st1False Value of i becomes 2 after if check as i++ increments it after the evaluation of i++ % 2 == 0
2nd2True3i becomes 3 after if check, hence 3 is printed in this iteration.
3rd3False i becomes 4.
4th4True5i becomes 5.
5th5False i becomes 6.
6th6True7i becomes 7.
7th7False i becomes 8.
8th8True9i becomes 9.
9th9False i becomes 10.

As value of i is now 10, the test condition of while loop becomes false hence, 10th iteration of the loop is not executed.

Answered By

4 Likes


Related Questions