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);
}
- 4
- 5
- 0
- 10
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:
| Iterations | i | i++ % 2 == 0 | Output | Remarks |
|---|---|---|---|---|
| 1st | 1 | False | Value of i becomes 2 after if check as i++ increments it after the evaluation of i++ % 2 == 0 | |
| 2nd | 2 | True | 3 | i becomes 3 after if check, hence 3 is printed in this iteration. |
| 3rd | 3 | False | i becomes 4. | |
| 4th | 4 | True | 5 | i becomes 5. |
| 5th | 5 | False | i becomes 6. | |
| 6th | 6 | True | 7 | i becomes 7. |
| 7th | 7 | False | i becomes 8. | |
| 8th | 8 | True | 9 | i becomes 9. |
| 9th | 9 | False | 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.
Related Questions
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); }- 15
- 21
- 5
- 0
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); }- 5
- 0
- 15
- Infinite loop
State whether the following statement is True or False :
To execute a do-while loop, the condition must be true in the beginning.
State whether the following statement is True or False :
The while loop is an exit-controlled loop.