Arithmetic Operators
Operators | Symbol | Example |
Addition | + | x+y |
Subtraction | - | a-b |
Division | / | x/y |
Multiplication | * | a * b |
Modulus | % | a%b |
- Modulus is used to get the remainder after dividing two numbers. Rest of the operators are already known to you.
- Some operators have default precedence over others as like Multiplication operator has higher precedence over the addition operator.
- It works according to the BODMAS (Bracket Of Division Multiplication Addition Subtraction) rule of Mathematics.
For Example:
#include<iostream>
using namespace std;
int main(){
int x = 8+2*2;
cout<<x; // Output will be 12
}
- To overcome Operator precedence, we may use brackets
#include<iostream>
using namespace std;
int main(){
int x = (8+2)*2;
cout<<x; // Output will be 20
}
Assignment Operators (Shorthand):
- Equal to (=) operator is used as an assignment operator that assigns its right side to its left side also.
For Example:
#include <iostream>
using namespace std;
int main(){
int x = 10;
x+=5; // x=x+5
x*=8; // x=x*8
x/=4; // x=x/4
x%=9; // x=x%9;
}
Increment operator:
- To get an increment of 1 for a variable, we use ++ sign after that variable. Like x++.
For Prefix:
++x;
For Postfix:
X++;
Decrement Operator:
- Decrement operator helps to get a decrement value.
For Prefix:
- -x;
For Postfix:
x- -;
#include <iostream>
using namespace std;
int main(){
int x = 10;
int y;
y=x- -;
cout<<y<<endl; //Output will be 10
cout<<x<<endl; //Output will be 9
cout<<- -y<<endl; //Output will be 9
cout<<y; //Output will be 9
}
Concept of Prefix and Postfix:
Prefix(++x) | Postfix(x++) |
Increments the value and then proceeds with the expression Example: #include <iostream> using namespace std; int main(){ int x = 10; int y = ++x; cout<<x<<endl; //Output will be 11 cout<<y<<endl; //Output will be 11 } | Evaluates the expression and then perform the incrementing Example: #include <iostream> using namespace std; int main(){ int x = 10; int y = x++; cout<<y<<endl; //Output will be 10 cout<<x<<endl; //Output will be 11 } |
How it works: int x = 10;x = x+1;int y = x; | How it works: int x = 10;int y = x;x = x+1; |
Relational Operators:
Operator | Symbol | Example |
Greater Than | > | 9>4 |
Less Than | < | 4<6 |
Greater Than Equal To | >= | 8>=4 |
Less Than Equal To | <= | 6<=9 |
Equal To | == | 5==5 |
Not Equal To | != | 5!=4 |