KnowledgeBoat Logo

Computer Applications

How many times are the following loop bodies repeated? What is the final output in each case?

int z = 2;
while (z < 20)
    if ((z++) % 2 == 0) 
        System.out.println(z);

Java

Java Iterative Stmts

3 Likes

Answer

The loop repeats for 18 times.

3
5
7
9
11
13
15
17
19

Working

The loop executes 18 times. Value of z is printed 9 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
1st2True3Value of z becomes 3 after if check as z++ increments it after the evaluation of (z++) % 2 == 0. Hence, 3 is printed.
2nd3Falsez becomes 4 after if check
3rd4True5z becomes 5.
4th5Falsez becomes 6.
5th6True7z becomes 7.
6th7Falsez becomes 8.
7th8True9z becomes 9.
8th9Falsez becomes 10.
9th10True11z becomes 11.
10th11Falsez becomes 12.
11th12True13z becomes 13.
12th13Falsez becomes 14.
13th14True15z becomes 15.
14th15Falsez becomes 16.
15th16True17z becomes 17.
16th17Falsez becomes 18.
17th18True19z becomes 19.
18th19Falsez becomes 20.

As value of z is now 20, the test condition of while loop becomes false hence, 19th iteration of the loop is not executed.

Answered By

1 Like


Related Questions