How to make sense of modulo in c

i am not understanding this modulo in c languge.
For example:

#include <stdio.h>
#include<math.h>
int main()
{ int my_input[] = {23, 22, 21, 20, 19, 18}; int n, mod; int nbr_items = sizeof(my_input) / sizeof(my_input[0]); for (n = 0; n < nbr_items; n++) { mod = my_input[n] % 4; printf("%d modulo %d --> %d\n", my_input[n], 4, mod); }
}

Gives:

23 modulo 4 --> 3
22 modulo 4 --> 2
21 modulo 4 --> 1
20 modulo 4 --> 0
19 modulo 4 --> 3
18 modulo 4 --> 2

I would have expected a number that i can make sense of.
Essentially i am trying to test if a number is divisible by 4.

5

2 Answers

The modulo operator in C will give the remainder that is left over when one number is divided by another. For example, 23 % 4 will result in 3 since 23 is not evenly divisible by 4, and a remainder of 3 is left over.

If you want to output whether or not a number is divisible by 4, you need to output something other than just the mod result. Essentially, if mod = 0 than you know that one number is divisible by another.

If you want to output whether or not the number is divisible by 4, I would suggest creating a new character that is set to "y" (yes) or "n" (no) depending on the result of the mod operation. Below is one possible implementation to generate a more meaningful output:

#include <stdio.h>
#include <ctype.h>
#include <math.h>
int main()
{ int my_input[] = {23, 22, 21, 20, 19, 18}; int n, mod; char is_divisible; int nbr_items = sizeof(my_input) / sizeof(my_input[0]); for (n = 0; n < nbr_items; n++) { mod = my_input[n] % 4; is_divisible = (mod == 0) ? 'y' : 'n'; printf("%d modulo %d --> %c\n", my_input[n], 4, is_divisible); }
}

This will give the following:

23 modulo 4 --> n
22 modulo 4 --> n
21 modulo 4 --> n
20 modulo 4 --> y
19 modulo 4 --> n
18 modulo 4 --> n
1

I'm sure we know the basic division equation from high school math

dividend = divisor*quotient + remainder

Now:
1. The "/" operator gives us the quotient.
2. The "%" operator gives us the remainder

example:

 say a = 23, b = 4 a / b = 23 / 4 = 5 a % b = 23 % 4 = 3 23 = 4*5 + 3 

Here 4 is the quotient and 3 is the remainder.

If a number is perfectly divisible by a divisor, then remainder is zero.

So:

 20/4 = 5 (quotient) 20%4 = 0 (remainder)

To test if a no if divisible by 4, the check should be something like if (num % 4 == 0).
Hope this helps!

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like