Operators and expressions
Do math in C - and learn the two surprises everyone hits: integer division and operator precedence.
- Use arithmetic, comparison and assignment operators
- Predict the result of integer division and
% - Convert between types with casts
An expression is anything that produces a value: 3 + 4, price * quantity, x > 10. C has a rich set of operators for building them. Most behave the way you expect from math class - with a couple of important exceptions.
Arithmetic
+ add, - subtract, * multiply, / divide, and % (modulo) gives the remainder of integer division. % is surprisingly useful: n % 2 == 0 tests whether n is even, and n % 10 gives its last digit.
1#include <stdio.h>
2
3int main(void) {
4 int a = 17, b = 5;
5 printf("%d + %d = %d\n", a, b, a + b);
6 printf("%d / %d = %d\n", a, b, a / b);
7 printf("%d %% %d = %d\n", a, b, a % b);
8 return 0;
9}17 + 5 = 22 17 / 5 = 3 17 % 5 = 2
Casts: converting types
A cast converts a value to another type: (double)a turns the integer in a into a double for that expression. C also converts automatically when you mix types - an int combined with a double is promoted to double. Assigning a double to an int silently drops the fraction, which -Wall can warn you about.
1#include <stdio.h>
2
3int main(void) {
4 int sum = 7;
5 int count = 2;
6 double wrong = sum / count;
7 double right = (double)sum / count;
8 printf("wrong: %.1f\n", wrong);
9 printf("right: %.1f\n", right);
10 return 0;
11}wrong: 3.0 right: 3.5
Notice wrong: storing the result in a double does not help, because the integer division already happened on the right-hand side. Convert before dividing.
Precedence
Like math, *, / and % happen before + and -: 2 + 3 * 4 is 14. Operators of equal precedence mostly go left to right: 10 - 4 - 3 is 3. When in doubt, add parentheses - they cost nothing and make intent obvious to the next reader.
Assignment shortcuts
C has compact forms for updating a variable:
x += 5;meansx = x + 5;(also-=,*=,/=,%=)x++;and++x;add 1;x--;and--x;subtract 1
x++ produces the old value and then increments; ++x increments first. On a line by itself the difference does not matter. Inside a bigger expression it does, and mixing ++ with other uses of the same variable in one expression can be undefined - keep increments on their own line.
Comparisons and logic
Comparison operators - ==, !=, <, >, <=, >= - produce 1 for true and 0 for false. Combine them with && (and), || (or) and ! (not). You will use these constantly in the next unit to make decisions.
Key takeaways
Integer
/truncates (7 / 2is3) and%gives the remainder. Cast before dividing to get a decimal:(double)a / b.*,/,%bind tighter than+,-. Use parentheses when in doubt.x += nandx++are shortcuts;==compares,=assigns.
Lesson quiz
6 questions · pass with 5 correct · up to 50 XP
Passing this quiz completes the lesson and keeps your streak going. Questions you miss come back in review sessions later.
Practice: write C
These run for real. Write the program, press Run tests, and read what the compiler tells you - learning to read compiler messages is half of learning C.
Minutes to hours
The variable total_minutes holds a number of minutes. Print it as hours and minutes, like this for 135:
135 minutes is 2h 15mUse integer division and % - no loops needed.
- Prints 2h 15m
Your code is compiled with gcc 14 (-Wall -Wextra) and run on Compiler Explorer (godbolt.org), a free public service.
A proper average
Three integer test scores are given. Print their average with two decimal places:
Average: 84.33Watch out for integer division.
- Prints 84.33
Your code is compiled with gcc 14 (-Wall -Wextra) and run on Compiler Explorer (godbolt.org), a free public service.
Questions about this lesson
Stuck? Ask. Figured something out? Share it. Explaining is one of the best ways to learn.
Loading posts…