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

Trace this program and find out what is the output. Explain how did you obtain t

ID: 3545316 • Letter: T

Question

Trace this program and find out what is the output. Explain how did you obtain the result (please change a to b in main).

#include <iostream>
using namespace std;

int f(int a)
{
     if (a>0)
           a--;
     else
           a++;
     return a;
}
int g( int b)
{
      int a = b-3;
      if (a <0)
         b = f(a);
      else
         b = f(-a);
      return b;
}
int main()
{
     int b = 4, x = 2;
     x = g(b);
     cout << " X = " << x << " b  = " << b << endl;
     b = g(x);
     cout << " X = " << x << " b  = " << b << endl;
     x = f(-x);
     b = g(-b);
     cout << " X = " << x << " b  = " << b << endl;
    return 0;
}

Explanation / Answer

int b = 4, x = 2;
// since b is 4 here
// g(4) will be called
// inside g(b) function
// a = 4-3 = 1
// since a = 1 > 0 b = f(-a) = f(-1) will be called/
// inside f(-1) function
// since -1<0 else block will be executed and -1++ = 0 will be returned
// b = f(-1) = 0 here and 0 will be returned back to function thus.
x = g(b);
cout << " X = " << x << " b = " << b << endl;
// this will print.   X = 0 b = 4
b = g(x);
// since x = 0 here g(0) will be called...
// inside g(b) function
// a = 0-3 = -3
// since a = -3 < 0 b = f(a) = f(-3) will be called/
// inside f(-3) function
// since -3<0 else block will be executed and -3++ = -2 will be returned
// b = f(-3) = -2 here and -2 will be returned back to function thus.
cout << " X = " << x << " b = " << b << endl;
// this will print.   X = 0 b = -2
x = f(-x);
// x is 0 here
// thus f(0) will be called. else block will be called returns 0++ = 1
// thus x = 1 will be assigned.
b = g(-b);
// g(-(-2)) = g(2) will be called.
// inside g(b) function
// a = 2-3 = -1
// since a = -1 < 0 b = f(a) = f(-1) will be called/
// inside f(-1) function
// since -1<0 else block will be executed and -1++ = 0 will be returned
// b = f(-1) = 0 here and 0 will be returned back to function thus.
cout << " X = " << x << " b = " << b << endl;
// this will print.    X = 1 b = 0

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