What is the difference between while (n--) and while (n = n-1)?

What is the difference between while(n--)and while(n=n-1)? When I use while(n=n-1)in my code, I can enter less than 1 number.

Example: first input 3, than input 3 times by one number (but this does not happen in while(n=n-1)). But when I use while(n--), this is normal.

My code is:

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

int main()
{
    int n;
    long long inum;
    scanf("%d", &n);
    while(n--)
    {
        scanf("%lld", &inum);
        if(inum == 0 || inum % 2 == 0)
        {
            printf("even\n");
        }

        else
        {
            printf("odd\n");
        }
    }

    return 0;
}
+4
source share
2 answers

while(n--)uses nin its body, and the decremented value is used for the next iteration.

while(n=n-1)matches with while(--n), which reduces and uses this new value nin its body.

-1
source

Value n--is the previous value.n

int n = 10;
// value of (n--) is 10
// you can assign that value to another variable and print it
int k = (n--);                     // extra parenthesis for clarity
printf("value of n-- is %d\n", k);

n = n - 1 1 n

int n = 10;
// value of (n = n - 1) is 9
// you can assign that value to another variable and print it
int k = (n = n - 1);                     // extra parenthesis for clarity
printf("value of n = n - 1 is %d\n", k);
+4

Source: https://habr.com/ru/post/1615442/


All Articles