Introduction to Operators:
An operator does some operations on operands and the operation done is normally specified by operator's symbol.
In the example below, we use + operator to add two integers.
#include <iostream> using namespace std; int main() { int num1, num2, result; //Declarations of num1, num2 & result variable num1 = 5; //Assigning integer 5 to variable `num1` num2 = 7; //Assigning integer 7 to variable `num2` result = num1 + num2; //Storing the result of addition in `result` cout < < result; //Displays the result return 0; }
Program Output:
12
Arithmetic Operators:
Operators used to perform common mathematical operations are known as arithmetic operators.
| Operator | Description | Example |
|---|---|---|
| Addition (+) | Used for adding two or more values. | num1 + num2 |
| Subtraction (-) | Used for subtracting one value from another. | num1 - num2 |
| Multiplication (*) | Used for multiplying two or more values. | num1 * num2 |
| Division (/) | Used for dividing one value by another. | num1 / num2 |
| Modulus (%) | Returns the division remainder | num1 % num2 |
| Increment (++) | Increases the value of a variable by 1 | a++ |
| Decrement (--) | Decreases the value of a variable by 1 | a-- |
Relational Operators:
Operators used for comparing numeric, character or logical data are known as Relational Operators. The result of comparision can be either true or false.
| Operator | Description | Example |
|---|---|---|
| Equal to (==) | Checks if two values are equal. | num1 == num2 |
| Not Equal to (!=) | Checks if two values are not equal. | num1 != num2 |
| Greater than (>) | Checks if the left value is greater than right | num1 > num2 |
| Less than (<) | Checks if the left value is less than right | num1 < num2 |
| Greater than equal to (>=) | Checks if the left value is greater than equal to right | num1 >= num2 |
| Less than equal to (<=) | Checks if the left value is less than or equal to right | num1 <= num2 |
Assignment Operators:
Operators used for assigning values to the variables are called assignment operators. The left side operand of the assignment operator is a variable and right side operand of the assignment operator is a value.
| Operator | Description | Example |
|---|---|---|
| = | Assignment | x = 5; |
| += | Add and assign | x += 3 |
| -= | Subtract and assign | x -= 2 |
| *= | Multiply and assign | x *= 4 |
| /= | Divide and assign | x /= 2 |
| %= | Modulus and assign | x %= 2 |
Logical Operators:
Operators used to connect two or more conditions or expressions together are called logical operators.
| Operator | Description | Example |
|---|---|---|
| && | Logical AND | x && y |
| || | Logical OR | x || y |
| ! | Logical NOT | !x |
Congratulations!
You've mastered the essential operators in C++. Now, you're equipped to manipulate data like a pro.