Examples of Expressions

We have already seen the precedence of arithmetic operators. We have expressions for different calculations in algebraic form, and in our programs we write them in the form of C statements. Let’s discuss some more examples to get a better understanding.

We know about the quadratic equation in algebra, that is y = ax2 + bx + c. The quadratic equation in C will be written as y = a * x * x + b * x + c. In C, it is not an equation but an assignment statement. We can use parentheses in this statement, this will make the expression statement easy to read and understand. Thus we can rewrite it as y = a * (x * x) + (b * y) + c.

Note that we have no power operator in C, just use * to multiply the same value.

Here is another expression in algebra: x = ax + by + cz2. In C the above expression will be as:

x = a * x + b * y + c * z * z

The * operator will be evaluated before the + operator. We can rewrite the above statement with the use of parentheses. The same expressions can be written as:

x = (a * x) + (b * y) + c * ( z * z)

Lets have an other expression in algebra as x = a(x + b(y + cz2)). The parentheses in this equation forces the order of evaluation. This expression will be written in C as:

x = a * (x + b * (y + c * z * z))

While writing expressions in C we should keep in mind the precedence of the operators and the order of evaluation of the expressions (expressions are evaluated from left to right). Parentheses are used in complicated expressions. In algebra, there may be curly brackets { } and square brackets [ ] in an expression but in C we have only parentheses ( ). Using parentheses, we can make a complex expression easy to read and understand and can force the order of evaluation. We have to be very careful while using parentheses, as parentheses at wrong place can cause an incorrect result. For example a statement x = 2 + 4 * 3 results x = 14. As * operator is of higher precedence, 4 * 3 is evaluated first and then result 12 is added to 4 which gives the result 14. We can rewrite this statement, with the use of parentheses to show it clearly, that multiplication is performed first. Thus we can write it as x = 2 + (4 * 3). But the same statement with different parentheses like x = (2 + 4) * 3 will give the result 18, so we have to be careful while using parenthesis and the evaluation order of the expression.

Similarly the equation (b^2 – 4ac)/2a can be written as ( b * b – 4 * a * c) / ( 2 * a ). The same statement without using parentheses will be as b * b – 4 * a * c / 2 * a. This is wrong as it evaluates to b^2 – 4ac/2a (i.e. 4ac is divided by 2a instead of (b^2-4ac)).

For previous lesson click here: Sample Program
For next lesson click here: Use of Operators


the easiest way to learn programming
introduction to programming
Examples of Expressions

0 comments:

Post a Comment

 

introduction to programming Copyright © 2011-2012 | Powered by Blogger