In C, the modulus operator (%) is used to find the remainder of a division between two integers.
While the / operator gives you the quotient (how many times a number fits), the % operator gives you what is "left over."
1. Basic Example
If you calculate 10 % 3:
- 3 goes into 10 three times (3 \times 3 = 9).
- The difference between 10 and 9 is 1.
- Therefore,
10 % 3equals1.
2. How it's used in your lab
In your code, you see this line:
int secret_number = rand() % 10 + 1;
This is a very common trick in C to limit a range:
rand() % 10: Any number divided by 10 will result in a remainder between 0 and 9.+ 1: By adding 1, you shift that range from0-9to1-10.
3. Key Rules
- Integers only: The modulus operator only works with integer types (
int,char,long, etc.). You cannot use it with floating-point numbers (floatordouble). - Division by Zero: Just like regular division, you cannot perform
x % 0. This will cause a runtime error (crash).
Common Real-World Uses
- Checking for even/odd:
if (number % 2 == 0)means the number is even. - Keeping track of cycles:
Like converting total seconds into "seconds within a minute" (total_seconds % 60). - Restricting input:
Ensuring an index stays within the bounds of an array (like we did with the random number).
Does that help clarify why we used it to set the range for the guessing game?