KnowledgeBoat Logo

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

5 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:

Iterationsz(z++) % 2 == 0OutputRemarks
1st1False Value of z becomes 2 after if check as z++ increments it after the evaluation of (z++) % 2 == 0
2nd2True3z becomes 3 after if check, hence 3 is printed in this iteration.
3rd3False z becomes 4.
4th4True5z becomes 5.
5th5False z becomes 6.
6th6True7z becomes 7.
7th7False z becomes 8.
8th8True9z becomes 9.
9th9False 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