Question

#include <stdio.h>
int main(){
    int i = 0;

    do {
        i++;
        printf("In while loop\n");
    } while (i < 3);
}

output:

In while loop
In while loop
In while loop

Why the printf statement is executed three times? As soon as the loop starts the value of i becomes 1, so the loop should run 2 times only but it is running 3 times, how?

Was it helpful?

Solution

Pseudo code:

i = 1
=> In while loop
i = 2
=> In while loop
i = 3
=> In while loop
exit from loop

The condition is checked only at the end, after printf.

OTHER TIPS

The do-while loop tests the condition at the end, so the loop in your example will be executed 3 times with i = 1, 2, 3.

Your condition(i < 3) is checked at the end of the loop.

    1st pass :  i = 1  => "In while loop" printed => (i < 3) satisfied.increment i
    2nd pass :  i = 2  => "In while loop" printed => (i < 3) satisfied.increment i
    3rd pass :  i = 3  => "In while loop" printed => (i < 3) not true.exit from loop

Hope this helps!

  • The first time you hit the while after the first printf i is 1. The loop continues.
  • The second time you hit the while after the second printf i is 2. The loop continues.
  • The third time you hit the while after the third printf i is 3. The loop now ends.

You have hit printf three times.

The loop is starting with 'i=0' and then entering the loop with "i++" and becoming 'i=1' then the condition is checked over "i" so in the last loop when 'i=3' the loop is executed and then checked for "i<3".So the loop is repeated thrice.

The reason is u are using post increment.

{

        int i = 0;

        do {

            i++; //first time -  0,second time - 1,third time - 2

            printf("In while loop\n");

        } while (i < 3);

    }

Use pre increment or while instead of do-while to see the difference

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top