Operators in C
Operator: It is a symbol that performs operation on data.
Assignment operator: This operator is used to store value into variable.
Syntax: variable = value; | Example: a = 10 a = b = 10; |
Example codes on Assignment operator:
#include<stdio.h> int main(){ short a, b, c, d; a = 10; b = a; c = a+b; d = sizeof(c); printf(“%d,%d,%d,%d \n”, a, b, c, d); return 0; } | #include<stdio.h> int main() { short a, b, c, d; a = 10; b = c = a; d = a+b+c; printf(“d val : %d \n”, d); return 0; } |
Arithmetic operators: performs all arithmetic operations on data.
- Operators are +, -, *, / , %
- Division(/) operator returns the quotient after division.
- Mod(%) operator returns remainder after division.
We cannot apply Mod(%) operation on decimal data:
#include <stdio.h> int main() { float a=5, b=2; printf(“Quotient : %f \n”, a/b); // prints 2.500000 printf(“Remainder : %f \n”, a%b); // Error: return 0; } |
We can specify the length of digits while displaying decimal value:
#include<stdio.h> int main() { float a=5, b=2; printf(“%.2f \n”, a/b); // prints 2.50 return 0; } |
Operators Priority: We need to consider the priority of operators if the expression has more than one operator. Arithmetic operators follow BODMAS rule.
Priority | Operator |
() | First. If nested then inner most is first |
*, / and % | Next to (). If several, from left to right |
+, – | Next to *, / , %. If several, from left to right |
Examples expressions with evaluations:
5+3-2 8-2 6 | 5*3%2 15%2 1 | 5+3*2 5+6 11 | (5+3)*2 8*2 16 |