-3
for(i=0;i++<10;)
    {
        printf("%d\n",i);
    }

Why is it printing 1 to 10?

I know post increment happens after a loop, so why is it not showing 0? And why is it showing 10?

I wrestled a bear once.
  • 22,983
  • 19
  • 69
  • 116
azmain
  • 19
  • 4

3 Answers3

0

No .. in for loop first condition is checked.. and after that you are printing i For loop chart

N Kumar
  • 1,302
  • 1
  • 18
  • 25
0

I think what you're looking for is do..while

i=0;
do{
   printf("%d\n",i);
}while(i++<10);
I wrestled a bear once.
  • 22,983
  • 19
  • 69
  • 116
  • Thanks but As per your do..while loop it's printing 0 to 10. And i need to know about the for loop explanation. @Pamblam – azmain Oct 05 '15 at 17:14
0

Let's label the elements of the loop:

for(/* 1 */ i=0; /* 2 */ i++<10; /* 4 */)
{
    /* 3 */ printf("%d\n",i);
}

Here's how things play out:

  1. i is initialized to 0;
  2. The result of i++ is compared to 10; as a side effect of this expression, i is incremented by 1;
  3. The updated value of i is printed out;
  4. If there were an expression here, it would be evaluated.

Steps 2 through 4 are repeated until i++ < 10 evaluates to false.

John Bode
  • 119,563
  • 19
  • 122
  • 198
  • So, when i++=10 ,the condition is false(i++<10).Then why it's printing the updated value of i as 10? – azmain Oct 05 '15 at 17:19
  • @AIN: Remember that the expression `i++` evaluates to the *current* value of `i`, and as a *side effect* adds 1 to `i`. So, imagine `i` is set to `9`. In the expression `i++<10`, `i++` evaluates to `9`, so the condition is true and the loop body is executed. However, after the expression has been evaluated, `i` now has the value of `10`, and this is what gets printed out. This is why the output ranges from `1` to `10`. – John Bode Oct 05 '15 at 18:26
  • @AIN: Another way of writing this would be `for( i = 0; i < 10; ) { i++; printf("%d\n", i); }` – John Bode Oct 05 '15 at 18:46