Operators are special symbols used in programming to perform operations on variables and values. In C++, operators are categorized into various types, including arithmetic, comparison, and logical operators. Here’s a detailed overview of each type.
Arithmetic operators are used to perform basic mathematical operations on numeric values.
| Operator | Description | Example |
|---|---|---|
+ |
Addition | a + b |
- |
Subtraction | a - b |
* |
Multiplication | a * b |
/ |
Division | a / b |
% |
Modulus (Remainder) | a % b |
Examples:
#include <iostream>
using namespace std;
int main() {
int a = 10, b = 3;
cout << "Addition: " << (a + b) << endl; // 13
cout << "Subtraction: " << (a - b) << endl; // 7
cout << "Multiplication: " << (a * b) << endl; // 30
cout << "Division: " << (a / b) << endl; // 3 (integer division)
cout << "Modulus: " << (a % b) << endl; // 1
return 0;
}
Comparison operators are used to compare two values. They return a boolean value (true or false) based on the result of the comparison.
| Operator | Description | Example |
|---|---|---|
== |
Equal to | a == b |
!= |
Not equal to | a != b |
> |
Greater than | a > b |
< |
Less than | a < b |
>= |
Greater than or equal to | a >= b |
<= |
Less than or equal to | a <= b |
Examples:
#include <iostream>
using namespace std;
int main() {
int a = 10, b = 20;
cout << "Equal: " << (a == b) << endl; // false (0)
cout << "Not Equal: " << (a != b) << endl; // true (1)
cout << "Greater: " << (a > b) << endl; // false (0)
cout << "Less: " << (a < b) << endl; // true (1)
cout << "Greater or Equal: " << (a >= b) << endl; // false (0)
cout << "Less or Equal: " << (a <= b) << endl; // true (1)
return 0;
}
Logical operators are used to perform logical operations on boolean values. They are commonly used in conditional statements.
| Operator | Description | Example |
|---|---|---|
&& |
Logical AND | a && b |
| ` | ` | |
! |
Logical NOT | !a |
Examples:
#include <iostream>
using namespace std;
int main() {
bool a = true, b = false;
cout << "Logical AND: " << (a && b) << endl; // false (0)
cout << "Logical OR: " << (a || b) << endl; // true (1)
cout << "Logical NOT: " << (!a) << endl; // false (0)
// Combining logical operators
cout << "Combined: " << (a && !b) << endl; // true (1)
return 0;
}
Understanding these operators is crucial for controlling the flow of your program and performing necessary calculations, making them foundational elements in C++ programming.
Open this section to load past papers