Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

For loop why the variable out of the loop is "last index" + step?

I was just wondering why this :

int i;

for (i=0; i<5; i++){

    printf("%d\n",i)

}

printf("Here i get the result that misleads me : %d\n",i)

The last value is 5.

My logic is :

From 0 to 4 -> printf

If i > 4 (since we are dealing with integers) stop the loop.

But the loop stopped at 4 not 5 ! Why do I get 5 after the loop ? Why does it ever increment ?

Arbitrary ?

Thanks,

like image 749
Larry Avatar asked Oct 22 '25 12:10

Larry


2 Answers

There are three clauses in the for statement.

  1. The init-stmt statement is done before the loop is started, usually to initialize an iteration variable.
  2. The condition expression is tested before each time the loop is done. The loop isn't executed if the boolean expression is false (the same as the while loop).
  3. The next-stmt statement is done after the body is executed. It typically increments an iteration variable.

So, end of each for loop execution, increment operation executed, and, in the 4th iteration, value of i is 5 and the for loop was broke as the value is 5 in 5th iteration.

like image 86
Abimaran Kugathasan Avatar answered Oct 24 '25 03:10

Abimaran Kugathasan


unroll what's happening

int i = 0;

while( i < 5 )
{
   // body of for loop

   i++;
}

// i == 5 here as i must be greater than or equal to 5 to break out of while loop
like image 21
Moho Avatar answered Oct 24 '25 01:10

Moho



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!