Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading