Skip to content

Operators and Expressions

Programming C++ Difficulty 1/5

Beginning of the lesson

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 / 2 is 3 but 7.0 / 2 is 3.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. So 7 / 2 is 3, not 3.5.
  • If at least one side is a double (a number with a decimal point), C++ keeps the decimals. So 7.0 / 2 is 3.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.

Continue this lesson on YourAIZone

The full lesson has the complete explanation, worked examples, common mistakes, tests with instant checking and an AI tutor. Start right away as a guest, or create an account to keep your progress.

In the full lesson

  • The complete explanation
  • Worked examples
  • Common mistakes and how to avoid them
  • Test questions: 15
  • AI tutor that answers questions about the topic
  • Progress tracking for students, parents and teachers