An expression combines values, variables, and operators. Programs use expressions to calculate, join, compare, and update data.
Arithmetic operators
C supports addition, subtraction, multiplication, division, and modulo. Operand types affect the result.
When both operands are integers, / performs integer division and discards the fractional part.
printf("%d\n", 21 / 4); // 5The modulo operator % returns the remainder after integer division.
printf("%d\n", 22 % 3); // 1
printf("%d\n", 4 % 7); // 4KNOWLEDGE QUIZ
Reversing a three-digit integer
Integer division and modulo are often used together to split an integer into digits.
printf("Enter a 3-digit integer: \n");
int num;
scanf("%d", &num);
int a = num / 100;
int b = num / 10 % 10;
int c = num % 10;
printf("Reversed: %d\n", (c * 100 + b * 10 + a));One possible run:
Enter a 3-digit integer: 520
Reversed: 25The result is displayed as 25 because the reversed number is 025, and leading zeros are not shown when printing an integer.
KNOWLEDGE QUIZ
Compound operators
Compound operators make variable updates shorter.
a += bmeansa = a + ba -= bmeansa = a - ba *= bmeansa = a * ba /= bmeansa = a / ba %= bmeansa = a % b
KNOWLEDGE QUIZ
Split total seconds into hours, minutes, and seconds
Break a total number of seconds into hours, minutes, and leftover seconds. It is a good way to reinforce integer division and % together.
- Read an integer named totalSeconds.
- Use integer division and modulo to compute hours, minutes, and seconds.
- Print the result in a format such as “3661 seconds = 1 hour 1 minute 1 second”.