Reputation: 53
What is the difference between while(n--)
and while(n=n-1)
? When I use while(n=n-1)
in my code, I can input less than 1 number.
Example: First input 3 than input 3 times a single number (but not happening this in while(n=n-1)
).
But when I use while(n--)
, it's 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;
}
Upvotes: 5
Views: 13386
Reputation: 7100
while(n--)
uses n
in its body, and the decremented value is used for the next iteration.
while(n=n-1)
is the same as while(--n)
, which decrements and uses this new value of n
in its body.
Upvotes: 1
Reputation: 108978
The value of n--
is the previous value of 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);
The value of n = n - 1
is 1 less than the previous value of 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);
Upvotes: 4