Sams Teach Yourself C in 21 Days

(singke) #1
The Pieces of a C Program: Statements, Expressions, and Operators 67

4


TABLE4.2 C’s binary mathematical operators
Operator Symbol Action Example
Addition + Adds two operands x + y
Subtraction - Subtracts the second x - y
operand from the first
operand
Multiplication * Multiplies two operands x * y
Division / Divides the first operand x / y
by the second operand
Modulus % Gives the remainder x % y
when the first operand is
divided by the second
operand

The first four operators listed in Table 4.2 should be familiar to you, and you should have
little trouble using them. The fifth operator, modulus, might be new. Modulus returns the
remainder when the first operand is divided by the second operand. For example, 11
modulus 4 equals 3 (that is, 4 goes into 11 two times with 3 left over). Here are some
more examples:
100 modulus 9 equals 1
10 modulus 5 equals 0
40 modulus 6 equals 4
Listing 4.2 illustrates how you can use the modulus operator to convert a large number of
seconds into hours, minutes, and seconds.

LISTING4.2 seconds.c: Demonstrates the modulus operator
1: /* Illustrates the modulus operator. */
2: /* Inputs a number of seconds, and converts to hours, */
3: /* minutes, and seconds. */
4:
5: #include <stdio.h>
6:
7: /* Define constants */
8:
9: #define SECS_PER_MIN 60
10: #define SECS_PER_HOUR 3600
11:
12: unsigned seconds, minutes, hours, secs_left, mins_left;
13:
14: int main( void )

07 448201x-CH04 8/13/02 11:15 AM Page 67

Free download pdf