Reputation: 433
Code
#include <stdio.h>
int main() {
int i;
for (i=1; i<=10; i++) {
(i % 2) ? printf("%d is odd\n", i) : printf("%d is even\n", i);
}
}
Result
1 is odd
2 is even
3 is odd
4 is even
5 is odd
6 is even
7 is odd
8 is even
9 is odd
10 is even
In the above C program, why it still works fine even though the conditional expression only states i%2
and not i%2!=0
?
Upvotes: 0
Views: 435
Reputation: 881323
In C, integers can be used in a Boolean context, and zero represents false while non-zero represents true.
That's why your code works. The expression num % 2
will be 0 (the single false value) for an even number and 1 (one of the many possible true values) for an odd number.
The following expressions would all work for detecting an odd number:
num % 2
(num % 2) != 0
((num % 2) != 0) != 0
... and so on, ad untilyougetboredum (like 'ad infinitum' but with limits).
Having said that, I don't really consider it a good idea to do it this way, code should express intent as much as possible and the intent here should be to choose the path of execution based on a comparison. That means, if you're looking for an odd number, you should use something like (num % 2) == 1
.
You also don't need a separate printf
call in each of those code paths:
printf("%d is %s\n", num, ((num % 2) == 1) ? "odd" : "even");
You'll notice I've also used num
instead of i
. This is simply a style thing of mine, related to the afore-mentioned intent. If the variable is only used as an index, I'm happy to use the i
-type variables(a) but, the second it gains a semantic property (like a number being checked for oddity), I tend to use more descriptive names.
I have no issue with people using simple variable names, I just prefer more descriptive ones in my own code.
(a) Actually, I'd probably use idx
in that case but that's being too CDO(b), even for me :-)
(b) OCD but in the right order :-)
Upvotes: 4
Reputation: 49
C doesn't have a dedicated boolean type. It uses int value as boolean. That is 0 is considered false
and any non zero value is treated as true
.
Try printing some conditions
printf("%d",5==5);
printf("%d",1>3);
This will output 1 and 0.
C always uses 1 to denote true
. But any other non-zero value would work as well when using in conditions.
if(6+1)
printf("TRUE");
Will print TRUE.
This is also the reason we can use this form of while loop:
int i= 10;
while(i--){
printf("%d",i);
}
Will print 9876543210
. Notice it stops when i becomes 0, which is false
.
Now back to the question, i%2
would always result in either 0 or 1. In case of 1(true) the first statement is run while in case of 0 (false) the second statement is run.
Upvotes: -1