Explain the modulus operator and provide an example of how it is used in programming.

Computer Science

ScanSolve AI Answer

Answer

The modulus operator (often represented by the % symbol) returns the remainder of a division operation.

For example, if you divide 10 by 3, the result is 3 with a remainder of 1. The modulus operator would return that remainder, which is 1.

Example in Python:

# Example 1: Basic modulus operation
result1 = 10 % 3
print(f"10 % 3 = {result1}") # Output: 1

# Example 2: Checking if a number is even or odd
number = 7
if number % 2 == 0:
    print(f"{number} is an even number.")
else:
    print(f"{number} is an odd number.") # Output: 7 is an odd number.

number = 12
if number % 2 == 0:
    print(f"{number} is an even number.") # Output: 12 is an even number.
else:
    print(f"{number} is an odd number.")
Was this helpful?

Still stuck on this one?

Ask a follow-up, and the answer starts from this question.

Got a different question?Ask your own question