Search code examples
cfor-loopdecrement

Output when using pre decrement in for loop in C


As you can see this the code in C, here I have used in for loop --i for decrement but I am not getting the expected output. Please explain

#include <stdio.h>
#include <stdlib.h>

int main() {
    int n, i = 1;
    printf("Enter the number ");
    scanf("%d", &n);
    while (i <= n) {
        printf("%d ", i++);
    }
    printf("\n");
    for (i = n; i >= 1; --i) {
        printf("%d ", i);
    }
   return 0;
}

I am getting the output for n=6.

1 2 3 4 5 6
6 5 4 3 2 1

but I am expecting it to be like this

1 2 3 4 5 6
5 4 3 2 1

Solution

  • Each for loop can be replaced with a while loop. The initializing statement (1st part of for) comes first, then the conditional loop (condition: 2nd part of for), and the loop statement (3rd part of for) is executed right before the loop repeats.

    Your loop:

        for (i = n; i >= 1; --i)
        {
            printf("%d ", i);
        }
    

    is equivalent to:

        i = n;
        while (i>=1)
        {
            printf("%d ", i);
            --i;
        }
    

    So the output is correct, and your expectation is wrong.


    But why has the for loop the loop statement in its parentheses, so that some beginners assume it executes before the loop body?

    This shows the coherence between all the loop's parts. Consider a loop body of multiple lines. The trailing loop statement (for example, increment the index) would be far away from the leading initialization statement and the condition. And this is more work for your brain to grasp.