## Operator Precedence :

Each operator in C has a precedence associated with it. This precedence is used to determine, how n expression involving more than one operator is evaluated.

There are distinct levels of precedence and an operator may belong to one of these levels.

The operators at the higher level of precedence are evaluated first and the operators of the same precedence are evaluated either from left to right or from right to left, depending upon the level. This is known as associativity property of an operator.

### Precedence of Arithmetic Operators:

An arithmetic expression involving parenthesis will be evaluated from left to right using the rules of precedence of operators. There are two distinct priority levels of arithmetic operators in C.

- High priority arithmetic operators are
***, /, %.** - Low priority arithmetic operators are
**+, -.**

The basic evaluation procedure includes two left - to -right passes through the expression. During the first pass, the high priority operators are applied as they are encountered. During the first pass, the high priority operators are applied as they are encountered. During the second pass, the low priority operators are applied as they are encountered.

## Program : it explains the precedence and associativity of arithmetic operators

#include stdio.h main() { float a = 9, b = 12, c = 3, x, y, z; printf("Evaluation of expressions : "); x = a - b / 3 + c * 2 _ 1; y = a - b / (3 + c) * (2 - 1); z = a - (b / (3 + c) * 2) - 1; printf("x = %f ", x); printf("y = %f ", y); printf("Z = %f ", z); } Output : x = 10.000 7 = 7.00000 z = 4.0000

### Explaination :

Consider, the epxression 1 **x = a - b / 3 + c * 2 - 1**

when a = 9, b = 12, c = 3 the statement becomes, ** x = 9 - 12 / 3 + 3 * 2 - 1 **

The above expression is evaluated as follows :

First Pass: |
Step 1 : x = 9 - 4 + 3 * 2 - 1 Step 2 : x = 9 - 4 + 6 - 1 |

Second Pass: |
Step 3 : x = 5 + 6 - 1 Step 4 : x = 11 - 1 Step 5 : x = 10 |

Consider the expression 2

y = a - b / (3 + c) * (2 - 1) y = 9 - 12 / (3 + 3) * (2 - 1)

When parentheses are used, the expressions within the parentheses assume highest priority.

If two or more sets of parentheses appear one after the another, the expression contained in the left most set is evaluated first and the right most is the last.

First Pass: |
Step 1 : y = 9 - 12 / 6 * (2 - 1) Step 2 : y = 9 - 12 / 6 * 1 |

Second Pass: |
Step 3 : y = 9 - 2 * 1 Step 4 : y = 9 - 2 |

Third Pass : | Step 5 : y = 7 |

Consider the expression 3

z = a - (b / (3 + c) * 2) - 1 z = 9 - (12 / (3 + 3) * 2) - 1

The result is as follows

Step 1 : z = 9 - (12 / 6 * 2) - 1 Step 2 : z = 9 - (2 * 2) - 1 Step 3 : z = 9 - 4 -1 Step 4 : z = 5 - 1 Step 5 : z = 4

parentheses can be nested, in such cases evaluation will be done from the innermost.

## 0 Comments