Reputation: 103
I need to check the divisibility of a number in c. How can I use the modulus operatpr in C to check if a number is divisible by another number? I tried doing this:
if (file_int % 3) {
printf("Hoppity \n");
}
It didn't work, although file_int is equal to 9.
What did I do wrong?
Thanks
Upvotes: -1
Views: 1667
Reputation: 3381
The mod operator returns the remainder resulting from the division... since 9 is divisible by three with no remainder, the return would be zero.
However, conditional statements evaluates to true if non-zero, false if zero. You need to change it to (file_int % 3 == 0)
.
Upvotes: 0
Reputation: 3119
because if it is divisible by 3 file_int % 3
will be equal to 0, and the if block won't execute.
Try
if(file_int % 3 == 0) {
// do stuff
}
Upvotes: 1
Reputation: 2543
If the result of the modulus is 0, it is evenly divisible. It would appear you are looking for it to be not divisible by 3 to continue the loop, though your code snippet is not sufficient to confidently assume your intent.
Upvotes: 1
Reputation: 62975
if (file_int % 3)
is the same as if (file_int % 3 != 0)
, which is the opposite of what you want.
if (file_int % 3 == 0) {
printf("Hoppity \n");
}
// or
if (!(file_int % 3)) {
printf("Hoppity \n");
}
Upvotes: 3
Reputation: 245389
It didn't work because the operation will return 0 which will be treated as false.
You actually need:
if(!(file_int % 3)) {
printf("Hoppity \n");
}
Upvotes: 7