Example(s):Palindrome, prime, armstrong, "linear search", reverse etc.

Example(s):1575, 1632, 1539 (Only one at a time)

Login

[lwa]

Solved Problem
#JAVA#3728

Problem Statement - Expression evaluation problem

Evaluate the following expression using the correct precedence and other evaluation rules.
int a=0,b=1; double x=5.0;
double d= x*3/4 – b/4 + 20 – ++a + 22/7;

Before using this you should have copied the code by selecting the entire code and pressing cntrl-c. (Line numbers will not come in the copied code). After that open any of the service and press cntrl-v to paste in the given code area. Needs a bit of tweaking as per the link.

int a=0,b=1; double x=5.0; double d= x*3/4i – b/4 + 20 – ++a + 22/7;
As given in the problem statement

Solving in steps Step 1: 3.75 – 0 + 20 – 1 + 3
As x is double multiplication with 3 integer will keep it double. Then division will 4 will happen to make it 3.75. This is because * and / have same precedence but evaluated left to right.

b=1 and b/4 will become 0 due to integer division.

++ a will become 1

22/7 will become 3 due to integer division.

Step 2: 3.75 + 22
Double portion makes 3.75, Integer portion makes 22. Both will be added to yield double 25.75

Notes

It is important to traverse left to to right in an expression computation. Only brackets are evaluated first, but within brackets also we traverse left to right.

Common Errors

While calculating 0.5*3/4 we have to multiply first and then divide due to left to right order. If this expression is 0.5*(3/4) then result would be 0 as 3/4 in integer form would yield 0.