Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Sample questions Evaluate each of the following according to the C++ precedence

ID: 3683071 • Letter: S

Question

Sample questions

Evaluate each of the following according to the C++ precedence rules. In each case, show what value is stored in the variable on the left-hand side. SHOW YOUR WORK SO IT IS CLEAR WHICH OPERATION IS DONE FIRST, THEN SECOND, ETC., UNTIL THE FINAL ANSWER. DON’T SKIP STEPS.

Use these declarations and initial values for all parts:

int k = 1, a = 8, z = 2, b = 3;

double y = 4.3;

(i) y = 5.5 - b / 2.0 * z + a;

   y = 5.5 – (1.5*2) + 8

      = 5.5 – 3 + 8 = 10.5

(ii) k = a – 2 * abs(k – b) - 2;

    k = 8 – 2* abs(-2) - 2 = 8 – 2*2 – 2 = 2

(iii) k = a % 5 / z - 5 + b;

     k = 8 % 5 / 2 – 5 + 3 = 3/2 - 5 + 3 = -0.5

Show what is output by the following C++ code:

x = 12;

y = 14;

if (x < 10)

          if (y > 10)

                 cout << "Option 1" << endl;

           else

                 cout << "Option 2" << endl;

          else

                 if (y > 10)

                    cout << "Option 3" << endl;

           else

                    cout << "Option 4 " << endl;

Explanation / Answer

Expression Evaluation is according to precedence from left to right.
int k = 1, a = 8, z = 2, b = 3;
double y = 4.3;

(i) y = 5.5 - b / 2.0 * z + a;
y = 5.5 – (1.5*2) + 8
= 5.5 – 3 + 8 = 10.5
Step 1:   b/2.0-> 1.5
       5.5 – 1.5*2 + 8  
Step 2:   1.5/2-> 3
       5.5 – 3 + 8      
Step 3: 5.5 – 3-> 2.5
       2.5+8
Step 4:   2.5+8
       10;  
      
(ii) k = a – 2 * abs(k – b) - 2;
k = 8 – 2* abs(-2) - 2 = 8 – 2*2 – 2 = 2

Step 1: k-b -> -2
       8 – 2 * abs(-2) - 2
Step 2: abs(-2) -> 2
       8 – 2 * 2 - 2
Step 3: 2*2 -> 4
       8 – 4 - 2
Step 4: 8 - 4 -> 4
       4 - 2
Step 5: 4 - 2 -> 2

(iii) k = a % 5 / z - 5 + b;
k = 8 % 5 / 2 – 5 + 3 = 3/2 - 5 + 3 = -0.5
Step 1: 8 % 5 -> 3
       3/2 - 5 + 3
Step 2: 3/2 -> 1
       1 - 5 + 3
Step 3: 1-5 -> -4
       -4 + 3
Step 4: -4 + 3 -> -1

#include <iostream>
#include <stdlib.h>
using namespace std;

int main()
{

int x = 12;
int y = 14;
if (x < 10)
if (y > 10)
cout << "Option 1" << endl;
else
cout << "Option 2" << endl;
else if (y > 10)
cout << "Option 3" << endl;
else
cout << "Option 4 " << endl;
return 0;
}

OUTPUT:

Option 3

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote