Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

For loop confusion in c program

Tags:

c

for-loop

Why the loop is running from 2 to 7?

int i;    
for(i=1;i<=6;printf("\n%d\n",i))    
i++;

The output of this is

2
3
4
5
6
7

but limit of i is 6.

like image 928
Manpreet Sidhu Avatar asked Jun 01 '26 20:06

Manpreet Sidhu


2 Answers

The Syntax of a for loop is

for ( clause-1 ; expression-2 ; expression-3 ) statement

The execution is as below, quoting from C11, chapter §6.8.5.3, (emphasis mine)

The expression expression-2 is the controlling expression that is evaluated before each execution of the loop body. The expression expression-3 is evaluated as a void expression after each execution of the loop body. [....]

Here, i++ is the body and printf("\n%d\n",i) is the expression-3.

So, the order of execution would be something like

 i = 1;
 start loop

    i < = 6          //==> TRUE
    i++;            //i == 2
    printf         // Will print 2    ///iteration 1  done

    i < = 6         //==> TRUE
    i++;           //i == 3
    printf        // Will print 3   ///iteration 2  done
    .
    .
    .
    i < = 6         //==> TRUE
    i++;           //i == 6
    printf        // Will print 6   ///iteration 5  done

    i < = 6         //==> TRUE
    i++;           //i == 7
    printf        // Will print 7   ///iteration 6  done

    i < = 6 ==> FALSE

 end loop.
like image 158
Sourav Ghosh Avatar answered Jun 03 '26 14:06

Sourav Ghosh


A for loop like

for(i=1;i<=6;printf("\n%d\n",i))    
    i++;

is equivalent to

{
    i = 1;  // Initialization clause from for loop

    while (i <= 6)    // Condition clause from for loop
    {
        i++;  // Body of for loop

        printf("\n%d\n", i);  // "Increment" clause from for loop
    }

}

As you can see, the printf is done after the variable i is incremented, which of course means it will print the incremented value (2 to 7).

like image 33
Some programmer dude Avatar answered Jun 03 '26 12:06

Some programmer dude



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!