Operators and Expressions
Teaching C++ to do math, compare values, and make decisions
Big Idea: An operator is a symbol that tells C++ to do something with values, like
+ to add or < to compare. When you join values and operators together, you get an expression — and every expression works out to a single result.
By the end you will be able to:
- use arithmetic operators
+ - * / %, - compare values with
== != < > <= >=, - combine conditions with
&& || !, - predict how an expression is evaluated,
- explain why
7 / 2is3but7.0 / 2is3.5.
1. Arithmetic operators
These do everyday math. The only surprising one is % (called modulo): it gives the remainder after division. For example 7 % 3 is 1, because 3 goes into 7 twice with 1 left over.
#include <iostream>
using namespace std;
int main() {
int a = 7, b = 3;
cout << a + b << endl; // 10
cout << a - b << endl; // 4
cout << a * b << endl; // 21
cout << a / b << endl; // 2 (integer division)
cout << a % b << endl; // 1 (remainder)
return 0;
}
Output:
10
4
21
2
1
Notice
7 / 3 gave 2, not 2.33. We explain that next.2. Integer division vs floating division
This trips up almost every beginner. In C++, the type of the numbers decides the kind of division:
- If both sides are whole numbers (
int), C++ does integer division and throws away the fractional part. So7 / 2is3, not3.5. - If at least one side is a
double(a number with a decimal point), C++ keeps the decimals. So7.0 / 2is3.5.
#include <iostream>
using namespace std;
int main() {
cout << 7 / 2 << endl; // 3 both are int
cout << 7.0 / 2 << endl; // 3.5 one is double
cout << 7 / 2.0 << endl; // 3.5 one is double
double x = 7;
cout << x / 2 << endl; // 3.5 x is double
return 0;
}
Output:
3
3.5
3.5
3.5
To force a decimal answer, make one value a
double — for example write 7.0 instead of 7.