In C++, operators are symbols used to manipulate variables and values. They allow programs to perform calculations, comparisons, and logical evaluations.
Using the Addition Operator (+
)
Operators can be used to perform simple arithmetic operations. For example:
C++
x
using namespace std;
int main() {
int topSpeed = 200 + 50; // Adding two values
cout << "Top speed is: " << topSpeed << " km/h";
return 0;
}
This program adds 200
and 50
, storing the result (250
) in topSpeed
.
Operators can also combine variables and values, or multiple variables:
C++
using namespace std;
int main() {
int torque1 = 80 + 20; // 100 (80 + 20)
int torque2 = torque1 + 50; // 150 (100 + 50)
int totalTorque = torque2 + torque2; // 300 (150 + 150)
cout << "Total torque is: " << totalTorque << " Nm";
return 0;
}
Types of Operators in C++
C++ organizes operators into different categories:
- Arithmetic Operators → Perform mathematical calculations.
- Assignment Operators → Assign values to variables.
- Comparison Operators → Compare values.
- Logical Operators → Control decision-making logic.
- Bitwise Operators → Perform operations on binary values.
Arithmetic Operators
Arithmetic operators allow for common mathematical operations.
Operator | Name | Description | Example |
---|---|---|---|
+ | Addition | Adds two values | x + y |
- | Subtraction | Subtracts one value from another | x - y |
* | Multiplication | Multiplies two values | x * y |
/ | Division | Divides one value by another | x / y |
% | Modulus | Returns the remainder of division | x % y |
++ | Increment | Increases a variable’s value by 1 | ++x |
-- | Decrement | Decreases a variable’s value by 1 | --x |