186k views
5 votes
What is the output of this code?

int num = 12; int x = 20 while (num <= x) { num = num + 1; if (num*2 > x+num) { console.log(num); } }

User Alethes
by
7.3k points

1 Answer

2 votes

The output of the given code is 21.

Step-by-step explanation:

int num = 12;

int x = 20

while (num <= x)

12<=20 13<=20 14 <= 20 15 <= 20 16 <=20 17 <=20 18 <=20 19 <=20 20 <= 20

{

num = num + 1; num = 13 num= 14 num= 15 num=16 num= 17 num= 18 num= 19 num= 20 num= 21

if (num*2 > x+num)

{ 26 > 32 28>34 30> 36 32> 36 34> 37 36> 38 38> 39 40> 40 42> 41

console.log(num);

} }

So this above output happens while you execute the given code, hence the output will be 21.

Because, when the num is 20, the execution goes like the following:

while(num<=x) while (20 <=12) {

20= num+1 (20+1) =21

if(num*2> x+num)

if (42 > 41)

{ console.log(21))}

User Joe Love
by
7.1k points