Do Some Math
Use +, -, *, /, % to do basic math in C++.
We'll cover the following...
In this lesson, you’ll use C++ as a calculator. You’ll write simple math operations, see the results instantly, and learn how to combine numbers in code.
Goal
You’ll aim to:
Use arithmetic operators.
Perform addition, subtraction, multiplication, division, and modulo.
Display results using
cout
.
Your first calculation
Here is a C++ program that performs addition and prints the result on the screen.
#include <iostream>using namespace std;int main() {cout << 5 + 3 << endl; // Adds 5 and 3, then prints the result (8) and moves to a new linereturn 0;}
Simple addition—your C++ program does the math and prints it.
Try all the operators
Just like addition, C++ can perform all the basic arithmetic operations.
#include <iostream>using namespace std;int main() {cout << 5 + 3 << endl; // Additioncout << 10 - 4 << endl; // Subtractioncout << 6 * 7 << endl; // Multiplicationcout << 20 / 5 << endl; // Divisioncout << 10 % 3 << endl; // Modulo (remainder)return 0;}
Below are the five basic arithmetic operators, along with their syntax and results.
Arithmetic Operators
Operator | Description | Syntax for 7 and 4 | Results for 7 and 4 |
+ | Addition: Adds two operands | 7 + 4 | 11 |
- | Subtraction: Subtracts two operands | 7 - 4 | 3 |
* | Multiplication: Multiplies two operands | 7 * 4 | 28 |
/ | Integer division: Divides the first operand by the second and gives an integer quotient because both operands are integers | 7 / 4 | 1 |
% | Modulo: Returns the remainder when the first operand is divided by the second | 7 % 4 | 3 |
You’ve used all five basic arithmetic operators.
Mini challenge
Write a program that calculates the result of:
Your age*12 (months)
Number of weeks in a year (52*7)
The remainder of 17 divided by 4
#include <iostream>using namespace std;int main() {// Your code goes herereturn 0;}
If you’re stuck, click the “Show Solution” button.
Tips
Integer division in C++ drops any decimals.
%
only works with integers.You can mix math and text in a single
cout
.
What’s next?
You’ve calculated. Next up, store those values in variables—and reuse them like pros.