41.8k views
3 votes
What is the value of i after the following code is executed? int i = 1; while ( i < 10 ) { int j = 10; while ( j > i ) j--; i += j; }

1 Answer

4 votes

The value of "i" after executing the entire code will be "16"

Step-by-step explanation:

Initially the value of i will be 1. This value keeps changing after entering the while loop. Let me give you step by step result.

When i = 1, it checks whether i<10, enters the loop, initializes the "j" to 10 and again while loop runs till j>i. so before the outer while loop ends "i" is reinitialized using "i=i+j".

So When i = 1, the value of j after running inner while loop will be 1 and i will be reinitialized to 1+1 = 2, now i =2

So When i = 2, j =2, Reinitialized value of i = 4

So When i = 4, j = 4, Reinitialized value of i = 8

So When i = 8, j = 8, Reinitialized value of i = 16.

The loop will not get executed thereafter.

You can add the below statement, after "j--;" to understand better.

cout<<"i="<<i<<"," <<"j="<<j<<"\\";

User Atul Verma
by
4.4k points