Computer Applications
How many times are the following loop bodies repeated? What is the final output in each case?
int z = 1;
while (z < 10)
if((z++) % 2 == 0)
System.out.println(z);
Java Iterative Stmts
6 Likes
Answer
The loop executes 9 times.
Output
3
5
7
9
Explanation
The loop executes 9 times. Value of z
is printed 4 times inside the loop. The condition if((z++) % 2 == 0)
will be false when z
is odd and true when z
is even. Value of z
will be incremented after if check is performed due to post increment operator z++
. Execution of the loop is summarized in the table below:
Iterations | z | (z++) % 2 == 0 | Output | Remarks |
---|---|---|---|---|
1st | 1 | False | Value of z becomes 2 after if check as z++ increments it after the evaluation of (z++) % 2 == 0 | |
2nd | 2 | True | 3 | z becomes 3 after if check, hence 3 is printed in this iteration. |
3rd | 3 | False | z becomes 4. | |
4th | 4 | True | 5 | z becomes 5. |
5th | 5 | False | z becomes 6. | |
6th | 6 | True | 7 | z becomes 7. |
7th | 7 | False | z becomes 8. | |
8th | 8 | True | 9 | z becomes 9. |
9th | 9 | False | z becomes 10. |
As value of z
is now 10, the test condition of while loop becomes false
hence, 10th iteration of the loop is not executed.
Answered By
1 Like
Related Questions
Write a program to accept n number of input integers and find out:
i. Number of positive numbers
ii. Number of negative numbers
iii. Sum of positive numbers
Write a program using do-while loop to compute the sum of the first 50 positive odd integers.
How many times are the following loop bodies repeated? What is the final output in each case?
int y = 1; while (y < 10) if (y % 2 == 0) System.out.println(y++);
How many times are the following loop bodies repeated? What is the final output in each case?
int x = 1; while (x < 10) if(x % 2 == 0) System.out.println(x);