Operator Precedence in C++ with example

Definition:
                  The order in which different type of operators in an expression are evaluated is known as operator precedence.This is also some time known as hierarchy of operators.

Each operator has its own precedence level. If an expression contains different types of operators, the operators with higher precedence are evaluated before the operators with lower precedence. To solve the order of precedence in C++ language is a follows.

  1. Any expression given in parentheses is evaluated first.
  2. The multiplication * expression is solved and then division / operators in any expression.
  3. Then the plus sign + and minus - sign operators are solved.
  4. In any case where their are parentheses within parentheses, the expression of the inner parentheses will be solved first.  
Examples:
                                                                         10*(24/(5-2))+13
Following way to solve the equation in general terms.
  1. First of all the expression 5-2 will be evaluated. The answer will be 3.
  2. Secondly, 24 will be divided by the result of last line i.e 24/3 which gives value 8.
  3. Thirdly, 10 will be multiplied by 8 i.e giving a result 80.
  4. Finally, 80 will be added in 13 and the last result will be 93.
Example #2:
Write a program that solves the following expression given below.
                                                                     a*b/(-c*31%13)*d  
#include<iostream.h>
#include<conio.h>
void main()
{
int a,b,c,d,r;
clrscr();
a=45;
b=65;
c=14;
d=24;
r=a*b/(-c*31%13)*d;
cout<<"result of expression is : "<<r<<endl;
getch();
}

The result of expression is = -75

Post a Comment

 
Top