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

#include <iostream> #include <string> using namespace std; void swap(int a, int

ID: 639149 • Letter: #

Question

#include <iostream>

#include <string>

using namespace std;

void swap(int a, int b)

{

      int temp = a;

      cout<<"a and b have the following values at the start of swap"<<endl;

      cout<<"a = "<<a<<" and b = "<<b<<endl;

      a=b;

      b=temp;

      cout<<"a and b have the following values at the end of swap"<<endl;

      cout<<"a = "<<a<<" and b = "<<b<<endl;

}

int main()

{

      int a=111, b=222;

      cout<<"a and b have the following values before swap is called"<<endl;

      cout<<"a = "<<a<<" and b = "<<b<<endl;

      swap(a,b);

      cout<<"a and b have the following values after swap is called"<<endl;

      cout<<"a = "<<a<<" and b = "<<b<<endl;

      return 0;

}

Question 1:Are the variables a and b used in the function main the same a and b variables that are used in the function swap in the program in Step 1? Explain your answer.

Question 2:Were the values stored in the variables a and b in the function main swapped after the execution of the function swap in the program in Step 1? Explain your observations.

Explanation / Answer

#include <iostream>
#include <string>
using namespace std;
void swap(int a, int b)
{
      int temp = a;
      cout<<"a and b have the following values at the start of swap"<<endl;
      cout<<"a = "<<a<<" and b = "<<b<<endl;
      a=b;
      b=temp;
      cout<<"a and b have the following values at the end of swap"<<endl;
      cout<<"a = "<<a<<" and b = "<<b<<endl;
}
int main()
{
      int a=111, b=222;
      cout<<"a and b have the following values before swap is called"<<endl;
      cout<<"a = "<<a<<" and b = "<<b<<endl;
      swap(a,b);
      cout<<"a and b have the following values after swap is called"<<endl;
      cout<<"a = "<<a<<" and b = "<<b<<endl;
      return 0;
}
Question 1:Are the variables a and b used in the function main the same a and b variables that are used in the function swap in the program in Step 1
variables a and b are passed by value so those will be copied in function swap. so function swap will have copy of variables in function main.
so both are not same variables but copy of them.

Question 2:Were the values stored in the variables a and b in the function main swapped after the execution of the function swap in the program in Step 1?
No. because those variables a and b are passed by value so those will be copied in function swap. so variables in function swap are copy of variables a and b of
function main. since we changed only their copy in function swap not actual variables. they will not be swapped after function call in main.