Home > database >  Issue in incrementing numbers in Do while loop
Issue in incrementing numbers in Do while loop

Time:09-29

I'm learning and tinkering with the C programming language. Unfortunately, While learning and playing with the do-while loop, I'm confused. I wrote and ran a program to increment a variable from 1 to 100 with condition i<=100; the code ran successful, but when I changed the condition of the do-while loop to i==100, the output confuses me because only 1 is printed on the console. Please help.

The code below gives the expected output.

#include<stdio.h>
int main(){
    int i=1;
    do{
        printf("\n%d\n",i);
          i;
    } while(i<=100);

}

The code below gives output 1.

#include<stdio.h>
int main(){
    int i=1;
    do{
        printf("\n%d\n",i);
          i;
    } while(i==100);

}

Thank you.

CodePudding user response:

The second one loops if i == 100. It is not the truth (as i == 1) on the first iteration and loop exits.

CodePudding user response:

The do-while loop always executes once and then checks whether the condition holds true. If the condition is true, the loop executes again and then checks the condition.

In your case, the mandatory first pass prints the value of i and then increments it. Next, the condition is checked while(i==100). At this point, i is 2 and the condition fails resulting in the loop being terminated.

  • Related