In C++, there are symbols which tell the compiler to perform certain operations on variables. These symbols are known as **operators**. For example, **(+)** is an operator which is used for adding the values of two variables.

Let's see different types of operators in C++.

- Arithmetic Operators
- Relational Operators
- Increment and Decrement Operators
- Logical Operators
- Assignment Operators

## Arithmetic Operators

Arithmetic Operators are the type of operators which take numerical values (either literals or variables) as their operands and return a single numerical value.

Let's assume the values of 'a' and 'b' to be 8 and 4 respectively.

Operator | Description | Example |
---|---|---|

+ | Adds operands | a+b=12 |

- | Subtracts second operand from first | a-b=4 |

* | Multiplies both operands | a*b=32 |

/ | Divides numerator by denominator. | a/b=2 |

% | Modulus Operator returns the remainder of an integer division. | a%b=0 |

```
#include <iostream>
int main()
{
using namespace std;
int a = 42, b = 5;
cout << "sum = " << ( a + b ) << endl;
cout << "difference = " << ( a - b ) << endl;
cout << "product = " << ( a * b ) << endl;
cout << "remainder = " << ( a % b );
return 0;
}
```

difference = 37

product = 210

remainder = 2

**int a = 42, b = 5; - **As seen before, this statement declares two integer variables 'a' and 'b' and assigns them the values 42 and 5 respectively.

In the next statement, **sum =** will be printed as it is, since it is enclosed within **" "**. After that, the expression **( a + b )** will get evaluated and its value (42 + 5 = 47) will get printed. Thus, **sum = 47** will get printed. Similarly, other statements will get evaluated and printed on the screen.

We can also introduce a third variable to store the sum of the first two variables as done in the following example.

```
#include <iostream>
int main()
{
int a = 42, b = 5, c;
c = a + b;
std::cout < "sum = " < c;
return 0;
}
```

Here we declared a third integer variable 'c' and stored the value of **a + b** (42 + 5 = 47) in it, thus making its value 47. Finally, **sum = 47** gets printed.

When we divide two integers, the result is an integer. For example, **7/3 = 2** (not 2.33333).

To get the exact decimal value of the answer, at least one of numerator or denominator should have decimal(float).

All 7/3.0, 7.0/3 and 7.0/3.0 return 2.33333

```
#include <iostream>
int main()
{
using namespace std;
cout << (7/3) << endl;
cout << (7/3.0) << endl;
cout << (7.0/3) << endl;
cout << (7.0/3.0);
return 0;
}
```

2.33333

2.33333

2.33333

Let's see one more example of dividing two integers.

```
#include <iostream>
int main()
{
using namespace std;
int x = 5;
int y = 2;
cout << (x/y) << endl;
cout << (x/float(y)) << endl;
cout << (float(x)/y) << endl;
cout << (float(x)/float(y));
return 0;
}
```

2.5

2.5

2.5

This example was just to show you the use of type casting. We converted the integer values of 'x' and 'y' into float in the middle of our program and as per our need.

## Precedance of Operators

In Maths, you might have learned about BODMAS rule, but that rule is not applied here. If we have written more than one operation in one line, then which operation should be done first is governed by the following rules :- **Expression inside brackets '()' are evaluated first**. After that, this table is followed ( The operator at the top has higher precedence and that at the bottom has the least precedence ):

Operator | Associativity |
---|---|

++ -- ! | Right to left |

* / % | Left to right |

+ - | Left to right |

> >= < <= | Left to right |

== =! | Left to right |

&& | Left to right |

|| | Left to right |

= += -= *= /= %= | Right to left |

Let's consider an expression

**n = 4 * 8 + 7**

Since the priority order of multiplication operator ( * ) is greater than that of addition operator ( + ), so first 4 will get multiplied with 8 and after that 7 will be added to the product.

Suppose two operators have the same priority order in an expression, then the evaluation will start from left or right as shown in the above table.

For example, take the expression.

**10 / 5 + 2 * 3 -8**

Since the priorities of / and * are greater than those of + and -, therefore / and * will be evaluated first. Since / and * have the same priority order, so these will be evaluated from left to right simplifying to the following expression.

**2 + 2 * 3 - 8**

After /, * will be evaluated resulting in the following expression

**2 + 6 - 8**

Again + and - have the same precedence, therefore these will also be evaluated from left to right i.e. first 2 and 6 will be added after which 8 will be subtracted resulting in 0.

## Relational Operators

Relational Operators check the relationship between two operands. It returns 1 if the relationship is true and 0 if it is false.

Following is the list of relational operators in C++.

Again, assume the value of 'a' to be 8 and that of 'b' to be 4.

Operator | Description | Example |
---|---|---|

== | Equal to | (a == b) is false |

!= | Not equal to | (a != b) is true |

> | Greater than | (a > b) is true |

< | Less than | (a < b) is false |

>= | Greater than or equal to | (a >= b) is true |

<= | Less than or equal to | (a <= b) is false |

Let's see an example to understand the use of these operators.

```
#include <iostream>
int main()
{
using namespace std;
int a = 5, b = 4;
cout << (a == b) << endl;
cout << (a != b) << endl;
cout << (a > b) << endl;
cout << (a < b) << endl;
cout << (a >= b) << endl;
cout << (a <= b) << endl;
return 0;
}
```

1

1

0

1

0

In the above example, since the value of 'a' is not equal to 'b', therefore **(a == b)** (equal to) returned false and **(a !=b)** (not equal to) returned true.

Since the value of 'a' is greater than 'b', therefore **(a > b)** (greater than) and **(a >= b)** (greater than or equal to) returned true whereas **(a < b)** (less than) and **(a <= b)** (less than or equal to) returned false.

### Difference between = and ==

Although = and == seem to be same, but they are quite different fromn each other. **=** is the **assignment operator** while **==** is the **equality operator**.

= assign values from its right side operands to its left side operands whereas == compares values.

Take two examples.

**x = 5;**

**x == 5;**

By writing x = 5, we assigned a value 5 to x, whereas by writing x == 5, we checked if the value of x is 5 or not.

## Logical Operators

In C++, if we write **A and B**, then the expression is true if both A and B are true. Whereas, if we write **A or B**, then the expression is true if either A or B or both are true.

**A and B - Both A and B**

**A or B - Either A or B or both.**

The symbol for **AND** is **&&** while that of **OR** is **||**.

Again assume the value of 'a' to be 8 and that of 'b' to be 4.

Operator | Description | Example |
---|---|---|

&& | Logical AND. If both the operands are non-zero, then the condition becomes true | (a && b) is true |

|| | Logical OR. If any one or both the operands are non-zero, then the condition becomes true | (a || b) is true |

! | Logical NOT. It is used to reverse the condition. So, if a condition is true, ! makes it false and vice versa. | (!(false)) is true |

In **Logical AND (&&)** operator, if any one of the expression is false, the condition becomes false. Therefore, for the condition to become true, both the expressions must be true.

For example, **(3>2)&&(5>4)** returns true because both the expressions are true. Conditions (3>2)&&(5<4), (3<2)&&(5>4) and (3<2)&&(5<4) are false because atleast one of the expressions are false in each case.

For **Logical OR (||)** operator, the condition is only false when both the expressions are false. If any one expression is true, the condition returns true. Therefore, (3<2)||(5<4) returns false whereas (3>2)||(5<4), (3<2)||(5>4) and (3>2)||(5>4) returns true.

**Logical Not (!)** operator converts true to false and vice versa. For example, !(4<7) is true because the expression (4<7) is false and the operator ! makes it true.

```
#include <iostream>
int main()
{
using namespace std;
int a = 5, b = 0;
cout << "(a && b) = " << (a && b) << endl;
cout << "(a || b) = " << (a || b) << endl;
cout << "!(a>b) = " << !(a>b) << endl;
return 0;
}
```

(a || b) = 1

!(a>b) = 0

In the expression**(a && b)**, since the value of 'b' is 0, therefore the condition became false and thus returned 0. Since the value of 'a' is non-zero, therefore the expression **(a || b)** became true and thus returned 1. The expression (a>b) is true (since the value of 'a' is greater than 'b') and thus the expression **!(a>b)** became false.

## Assignment Operators

Assignment Operators are used to assign values from its right side operands to its left side operands. The most common assignment operator is **=**.

If we write **a = 10;** means that we are assigning a value '10' to the variable 'a'.

There are more assignment operators which are listed in the following table.

Operator | Description | Example |
---|---|---|

= | Assigns value of right operand to left operand | C = A+B is same as C = A + B |

+= | Adds the value of right operand to left operand and assigns the final value to the left operand | C += A is same as C = C + A |

-= | Subtracts the value of right operand from left operand and assigns the final value to the left operand | C -= A is same as C = C - A |

*= | Multiplies the value right operand to left operand and assigns the final value to the left operand | C *= A is same as C = C * A |

/= | Divides the value of left operand from right operand and assigns the final value to the left operand | C /= A is same as C = C / A |

%= | takes modulus using two operands and assigns the result to the left operand | C %= A is same as C = C % A |

Before going further, let's have a look at an example:

```
#include <iostream>
int main()
{
using namespace std;
int a = 7;
a = a+1;
cout << a << endl;
a = a-1;
cout << a << endl;
return 0;
}
```

7

**a = a+1** - '**=**' operator starts from right. eg.- if a is 4 and b is 5, then a = b will make a to 5 and b will remain 5.

a = a+b; - Similarly, since '+' has higher priority than '=', so, a+b will be calculated first.

In the exact same fashion, in **a = a+1**, a+1 will be calculated first since **+** has higher priority than **=**. Now, the expression will become **a = 8** making the value of 'a' equal to 8.

Similarly, **a = a-1** will make the value of 'a' equal to 7 again.

To understand this, consider the value of a variable 'n' as 5. Now if we write **n +=2**, the expression gets evaluated as **n = n+2** thus making the value of 'n' as 7 ( n = 5 + 2 ). Let's look at an example where different assignment operators are used.

```
#include <iostream>
int main()
{
using namespace std;
int a = 7;
cout << "a += 4 " << "Value of a: "<< (a += 4) << endl;
cout << "a -= 4 " << "Value of a: "<< (a -= 4) << endl;
cout << "a *= 4 " << "Value of a: "<< (a *= 4) << endl;
cout << "a /= 4 " << "Value of a: "<< (a /= 4) << endl;
cout << "a %= 4 " << "Value of a: "<< (a %= 4) << endl;
return 0;
}
```

a -= 4 Value of a: 7

a *= 4 Value of a: 28

a /= 4 Value of a: 7

a %= 4 Value of a: 3

In the above example, initially, the value of 'a' is 7.

The expression **a += 4 **gets evaluated as 'a = a+4' thus making the value of 'a' as 11. After this, the expression **a -= 4** gets evaluated as 'a = a-4' thus subtracting 4 from the current value of 'a' (i.e. 11) and making it 7 again. Similarly, other expressions will get evaluated.

## Increment and Decrement Operators

++ and -- are called increment and decrement operators respectively.

**++** adds 1 to the operand whereas **--** subtracts 1 from the operand.

**a++** increases the value of a variable 'a' by 1 and **a--** decreases the value of a by 1.

Similarly, **++a** increases the value of 'a' by 1 and **--a** decreases the value of a by 1.

In **a++** and **a--**, ++ and -- are used as **postfix** whereas in **++a** and **--a**, ++ and -- are used as **prefix**.

For example, suppose the value of a is 5, then a++ and ++a changes the value of 'a' to 6. Similarly, a-- and --a changes the value of 'a' to 4.

### Difference between Prefix and Postfix

While both a++ and ++a increases the value of 'a', the only difference between these is that a++ returns the value of 'a' before the value of 'a' is incremented and ++a first increases the value of 'a' by 1 and then returns the incremented value of 'a'.

Similarly, a-- first returns the value of 'a' and then decreases its value by 1 and --a first decreases the value of 'a' by 1 and then returns the decreased value.

An example will make the difference clear.

```
#include <iostream>
int main()
{
using namespace std;
int a=8, b=8, c=8, d=8;
cout << "a++ = " << a++ << endl;
cout << "++b = " << ++b << endl;
cout << "c-- = " << c-- << endl;
cout << "--d = " << --d << endl;
return 0;
}
```

++b = 9

c-- = 8

--d = 7

In **a++**, postfix increment operator is used with 'a' which first printed the current value of 'a' (8) and then incremented it to 9.

Similarly in **++b**, the prefix operator first added one to the current value of 'b' thus making it 9 and then printed the incremented value. The same will be followed for the decremented operators.

## sizeof

**sizeof()** operator is used to return the size of a variable. Suppose we have an integer variable 'i', so the value of sizeof(i) will be 4 because on declaring the variable 'i' as of type integer, the size of the variable becomes 4 bytes.

Look at the following example to find the size of int, char, float and double variables

```
#include <iostream>
int main()
{
using namespace std;
int i = 6;
int j;
char c;
float f;
double d;
cout << "size of integer variable i : " << sizeof(i) << endl;
cout << "size of integer variable j : " << sizeof(j) << endl;
cout << "size of character variable c : " << sizeof(c) << endl;
cout << "size of float variable f : " << sizeof(f) << endl;
cout << "size of double variable d : " << sizeof(d) << endl;
return 0;
}
```

size of integer variable j : 4

size of character variable c : 1

size of float variable f : 4

size of double variable d : 8

Here, sizes of character, float and double variables are 1, 4 and 8 bytes respectively, so **sizeof** operator applied to these returns 1, 4 and 8 respectively. Whenever we declare an integer variable, a space in the memory equal to 4 bytes gets occupied by it. It doesn't matter whether we assign a value to the variable or not, space will allocate. Since, both i and j are integer variables, therefore the sizes of both of these are 4 bytes, regardless of whether a value is assigned to these or not.

Let's see another example.

```
#include <iostream>
int main()
{
using namespace std;
int i = 6;
int j;
char c;
float f;
double d;
cout << sizeof(int) << endl;
cout << sizeof(char) << endl;
cout << sizeof(float) << endl;
cout << sizeof(double) << endl;
return 0;
}
```

1

4

8

Here we printed the sizes of int, char, float and double using sizeof operator, same as we did in the previous example, except for the difference that this time we directly passed the name of the **datatype** in the **sizeof** operator.

So, now anytime you need to know the size of any datatype, you can do so by using **sizeof** operator.

## Let's do some Math

What if you want to take out the sine, cos or log of a number?

Yes, we can perform such mathematical operations in C++.

All these functions are defined in the **cmath** library. Therefore, to use any such function in our program, we need to include this library in the beginning of our program. For this, we have to include the following code in the beginning of our program.

#include <cmath>

After importing the library, we can enjoy the different mathematical functions in C++.

Let's see some of the mathematical functions.

Function | Description |
---|---|

sin | Calculates the sine value of some angle in radians |

cos | Calculates the cosine value of some angle in radians |

ceil | Calculates the number which is equal to the integer just greater than the number passed |

floor | Calculates the number which is equal to the integer just smaller than the number passed |

fmin | Returns the smaller number among the numbers passed to it |

fmax | Returns the larger number among the numbers passed to it |

fabs | Calculates the absolute value of a number |

round | Rounds a float or a double to the nearest integer |

sqrt | Calculates the square root of a number |

pow | It takes two numbers as parameters and returns the value of the first number raised to the power equal to the second number |

log | Returns the logarithm of a number. |

Now let's see the examples of some of these functions.

### ceil

It calculates the number which is equal to the integer just greater than it. For example, if the number 4.56 is passed to the function, it will return 5.

```
#include <iostream>
#include <cmath>
int main ()
{
std::cout << ceil(4.7) << std::endl;
return 0;
}
```

### fabs

It returns the absolute value of the number passed to it. Absolute value of a number is the magnitude of the number with a positive sign. For example, the absolute value of 2 is 2 whereas the absolute value of -2 is also 2.

To take out the absolute value of -5.6, we have to write the following code.

```
#include <iostream>
#include <cmath>
int main ()
{
std::cout << fabs(-5.6) << std::endl;
return 0;
}
```

### pow

It takes two parameters and returns the value of the first parameter raised to the power equal to the value of the second parameter.

For example, the value of the number 3 raised to the power 2 is equal to multiplying three two times which is equal to 9 (= 3*3).

```
#include <iostream>
#include <cmath>
int main ()
{
std::cout << pow(3,2) << std::endl;
return 0;
}
```

### fmin and fmax

fmin and fmax returns the smaller and the greater among the two numbers passed to these functions.

```
#include <iostream>
#include <cmath>
int main ()
{
std::cout << "Smaller number : "<< fmin(2,4) << std::endl;
std::cout << "Larger number : "<< fmax(2,4) << std::endl;
return 0;
}
```

Larger number : 4

Don't practice until you get it right. Practice until you can't get it wrong.