Why the output of z variable is 19? How does that code works more clearly?

I am having the following program in c++;

#include <iostream>

int main() {
    int i=1, j=1, k=1, z=0;
    for (; i <= 10; i++)
        while(j <= 10) {
            j++;
            do {
                k++;
                z++;
            } while(k <= 10);
        }
    std::cout << z << " ";
}

The output is 19 when running and I cannot wrap my head why it is that.

I was expecting the return to be 10 because of the previous while(j<=10). I am missing something?

>Solution :

The do while loop that is a sub-statement of the while loop

while(j<=10) {
    j++;
    do {
        k++;
        z++;
  } while(k<=10);

is executed 10 times due to the condition of the while loop

while(j<=10) {

In the first iteration of the loop within the inner do-while loop the variable z becomes equal to 10. On the other hand, the variable k will be equal to 11 due to the condition of the do-while loop

    do {
        k++;
        z++;
  } while(k<=10);

In the next 9 iterations of the outer while loop the inner do while loop will iterate only one time because after the first iteration of the while loop the variable k will be greater than 10.

So after the first iteration of the while loop the variable z will be equal to 10 and in the next 9 iteration of the while loop the variable z will be increased only once.

That is do-while loops always have at least one iteration because their conditions are checked after executing their sub-statements.

Leave a Reply