✏️ Explanatory Question

Evaluation of Expressions and Hierarchy

👁 0 Views
📘 Detailed Answer
🟢 Easy
💡

Answer with Explanation

Evaluation of Expressions and Their Hierarchy

Question

(a) g = big / 2 + big * 4 / big - big + abc / 3 ;
    (abc = 2.5, big = 2, assume g to be a float)

(b) on = ink * act / 2 + 3 / 2 * act + 2 + tig ;
    (ink = 4, act = 1, tig = 3.2, assume on to be an int)

(c) s = qui * add / 4 - 6 / 2 + 2 / 3 * 6 / god ;
    (qui = 4, add = 2, god = 2, assume s to be an int)

(d) s = 1 / 3 * a / 4 - 6 / 2 + 2 / 3 * 6 / g ;
    (a = 4, g = 3, assume s to be an int)

(a) Expression Evaluation

g = big / 2 + big * 4 / big - big + abc / 3

Given:
big = 2
abc = 2.5

Step 1:
= 2 / 2 + 2 * 4 / 2 - 2 + 2.5 / 3

Step 2:
= 1 + 8 / 2 - 2 + 0.833

Step 3:
= 1 + 4 - 2 + 0.833

Step 4:
= 5 - 2 + 0.833

Step 5:
= 3 + 0.833

Final Answer:
g = 3.833

(b) Expression Evaluation

on = ink * act / 2 + 3 / 2 * act + 2 + tig

Given:
ink = 4
act = 1
tig = 3.2

Step 1:
= 4 * 1 / 2 + 3 / 2 * 1 + 2 + 3.2

Step 2:
= 4 / 2 + 1 * 1 + 2 + 3.2

Step 3:
= 2 + 1 + 2 + 3.2

Step 4:
= 5 + 3.2

Step 5:
= 8.2

Since 'on' is an integer:
Final Answer:
on = 8

(c) Expression Evaluation

s = qui * add / 4 - 6 / 2 + 2 / 3 * 6 / god

Given:
qui = 4
add = 2
god = 2

Step 1:
= 4 * 2 / 4 - 6 / 2 + 2 / 3 * 6 / 2

Step 2:
= 8 / 4 - 3 + 0 * 6 / 2

(2 / 3 gives 0 because integer division)

Step 3:
= 2 - 3 + 0

Step 4:
= -1 + 0

Final Answer:
s = -1

(d) Expression Evaluation

s = 1 / 3 * a / 4 - 6 / 2 + 2 / 3 * 6 / g

Given:
a = 4
g = 3

Step 1:
= 1 / 3 * 4 / 4 - 6 / 2 + 2 / 3 * 6 / 3

Step 2:
= 0 * 4 / 4 - 3 + 0 * 6 / 3

(1 / 3 = 0 and 2 / 3 = 0 because of integer division)

Step 3:
= 0 - 3 + 0

Final Answer:
s = -3

Operator Hierarchy Used

Priority Operators Description
1 () Parentheses
2 * / % Multiplication, Division, Modulus
3 + - Addition and Subtraction

Example Program in C

#include 

int main()
{
    float g;
    int on, s1, s2;

    float abc = 2.5;
    int big = 2;

    g = big / 2.0 + big * 4 / big - big + abc / 3;

    printf("g = %.3f\n", g);

    int ink = 4, act = 1;
    float tig = 3.2;

    on = ink * act / 2 + 3 / 2 * act + 2 + tig;

    printf("on = %d\n", on);

    int qui = 4, add = 2, god = 2;

    s1 = qui * add / 4 - 6 / 2 + 2 / 3 * 6 / god;

    printf("s = %d\n", s1);

    int a = 4, g2 = 3;

    s2 = 1 / 3 * a / 4 - 6 / 2 + 2 / 3 * 6 / g2;

    printf("s = %d\n", s2);

    return 0;
}

Program Output

g = 3.833
on = 8
s = -1
s = -3
Important Note:
In C language, integer division removes the fractional part. For example: 2 / 3 = 0 and 1 / 3 = 0 when both operands are integers.