Operators
An operator is a symbol that works with values, like + or >. C++ has operators to calculate, to compare, and to combine true/false answers.
Arithmetic operators
#include <iostream>
using namespace std;
int main() {
int a = 7;
int b = 2;
cout << a + b << "\n";
cout << a - b << "\n";
cout << a * b << "\n";
cout << a / b << "\n";
cout << a % b << "\n";
return 0;
}
Output:
9
5
14
3
1
Look at the fourth line: 7 / 2 gave 3, not 3.5. When both values are int, C++ does integer division. It keeps only the whole part of the answer and drops the rest. It does not round. The next lesson shows how to get 3.5.
The last operator, %, is called modulo. It gives the remainder of a division. 7 divided by 2 is 3, with 1 left over, so 7 % 2 is 1.
As in math, *, / and % happen before + and -. Use parentheses to change the order:
cout << 2 + 3 * 4 << "\n";
cout << (2 + 3) * 4 << "\n";
Output:
14
20
Comparison operators
A comparison asks a question, and the answer is a bool. The operators are == (equal), != (not equal), >, <, >= and <=. Put the comparison in parentheses when you print it:
int a = 7;
int b = 2;
cout << (a > b) << "\n";
cout << (a == b) << "\n";
Output:
1
0
7 > 2 is true, so it printed 1. 7 == 2 is false, so it printed 0. Be careful: "equal" is two equals signs, ==. A single = is assignment, which puts a value into a variable.
Logical operators
These combine bool values. && means AND: true only when both sides are true. || means OR: true when at least one side is true. ! means NOT: it turns true into false, and false into true.
bool hungry = true;
bool hasFood = false;
cout << (hungry && hasFood) << "\n";
cout << (hungry || hasFood) << "\n";
cout << !hungry << "\n";
Output:
0
1
0
hungry && hasFood is false (0), because hasFood is false. hungry || hasFood is true (1), because hungry is true. And !hungry is false.
Shortcuts
x += 3 is short for x = x + 3. There are also -=, *= and /=. x++ adds 1 to x, and x-- takes 1 away.
int x = 7;
x += 3;
x++;
cout << x << "\n";
Output:
11
x started at 7. Adding 3 made it 10, and x++ made it 11.
In the exercise, read two numbers and print the results of the arithmetic operators.