0

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.


  • It makes no difference here whether you pre- or post-increment. It does not happen until the end of the first loop. Since there is no side-effect, ++counter is the same as counter++. - Weather Vane
  • for ( counter = 1; counter++ <= 10;) - EOF
  • Why do you think it should be 2? - immibis
  • The increment code is executed after each loop iteration. I.e., after the printf. 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
  • Why is this C question marked as a duplicate of a Java question? - Pang

3 답변


1

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


0

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.


0

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.

Linked


Related

Latest