Home > Net >  Why is the value of n equal to 5 in the first iteration?
Why is the value of n equal to 5 in the first iteration?

Time:02-12

I have a question that why is the value of n being used in the first iteration is 5 and not 6. I checked it on stackeoverflow and there many of them said that in the first iteration the value of n is used and then it is decreased by 1 and used in the next iteration.

#include <stdio.h>

int main()
{
    int ans = 1, n = 6;

    while (n--)
    {
        printf("n = %d\n", n);

        if (n != 0)
        {
            ans *= n;
        }
    }

    printf("ans = %d", ans);

    return 0;
}



Output:
n = 5
n = 4
n = 3
n = 2
n = 1
n = 0
ans = 120

CodePudding user response:

n = 6;
while (n--) {
    // n is 5, then 4, 3, 2, 1, 0, then the while terminates
}
// n is -1

compare with

n = 6;
while (--n) {
    // n is 5, then 4, 3, 2, 1, then the while terminates
}
// n is 0

CodePudding user response:

while (n--)

  1. while checks if n is non zero. (n == 6)
  2. n is being decremented. (n == 5)
  3. Body of the while is executed. (5 is being printed)

To multiple from 6 you need to use do ... while loop

int main(void)
{
    int ans = 1, n = 6;

    do
    {
        printf("n = %d\n", n);
        ans *= n ? n : 1;
    }while (n--);

    printf("ans = %d", ans);

    return 0;
}

or

    while(n)
    {
        printf("n = %d\n", n);
        ans *= n;  // note you do not need to check if n != 0
        n--;
    }

CodePudding user response:

Given

int n, x;

Post-decrement:

n = 6;
x = n--;                // post-decrement 

The above is the same as

n = 6;
x = n;
n = n - 1;

So this prints 5 and 6:

printf("%d %d", n, x);  // 5 6

Pre-decrement:

n = 6;
x = --n;                // pre-decrement

The above is the same as

n = 6;
n = n - 1;
x = n;

So this prints 5 and 5:

printf("%d %d", n, x);  // 5 5

What pre- and post-decrement have in common is that the value of n is decreased by one, which is why you do not see 6 inside the loop.

If you want to loop from 6 to 1 (inclusive), it's simpler to use a for-loop:

for(n = 6; n; --n) {
    printf("n = %d\n", n);
    ans *= n;
}

which is similar to

n = 6;
while(n) {
    printf("n = %d\n", n);
    ans *= n;
    --n;
}

CodePudding user response:

The answer lies in the post decrement operator. Every time while (n--) is encountered, the value of n remains n and not n-1 as expected from the post decrement operator --.

while (n--) { // At first, n is 6 for this statement
    // n is 5 then 4, 3, 2, 1
}

On the same note,

for (int i = 0; i < n; i--) {
    // Some code
}

and

for (int i = 0; i < n; --i) {
    // Some code
}

have same values of i.

  • Related