This question already has an answer here:
When for statement is executed the value of counter variable has to be increased by one because I use pre-increment operator.
#include <stdio.h>
int main (void)
{
unsigned int counter ;
for ( counter = 1; counter <= 10; ++counter /*here is problem*/) {
printf( "%u\n", counter );
}
}
Problem -
When the program is executed, the value of counter variable initially is 1 instead of 2.
In a for
loop
for(first statement; second statement; third statement){//...};
the third statement which is generally used for updation, is executed at the end of each iteration, therefore your variable counter
would be 1
during the first iteration and becomes 2
at the end of first iteration.
If you want to make your counter
variable to be incremented at the start of iteration, then try using it ++counter
in the second statement of for loop this way :
for ( counter = 1; ++counter <= 10;)
Reason :
because, a for loop is a pre-test loop and condition which is generally the second statement is checked at the start of each iteration. So now your counter
is incremented at the start of each iteration
When for statement is executed then
at first time for loop's third statement is not checked weather you use an increment operator or condition that is given to the for loop but
when loop start to iterate then if you use any increment or decrements operator at third statement of for loop then it works and if you use any condition at third statement of for loop then your program will never end causing an infinite loop.
If you want the count to start from 2, you should initialize count in the for loop as
for ( counter = 2; counter <= 10; counter++) {
printf( "%u\n", counter );
}
C follows the following syntax for for loops
:
for ( init; condition; increment ) {
statement(s);
}
The init part here is where you make your initializations.
++counter
is the same ascounter++
. - Weather Vanefor ( counter = 1; counter++ <= 10;)
- EOFprintf
. Since you're not using the result of your increment expression, it makes no difference whether you use a pre- or post-increment operator. That only affects the value of the expression, e.g.x = ++counter;
vs.x = counter++;
- Tom Karzes