Implement a function void myswapint a int b It swayt two val
Implement a function void my_swap(int& a, int& b). It swayt two values of the actural parameters.
Solution
/*
To implement a function void my_swap(int& a, int& b) The call by reference method of passing arguments to a function copies the reference of an argument into the formal parameter. Inside the function, the reference is used to access the actual arguments used in the call. This means that changes made to the parameter affect the passed argument.
*/
#include <iostream>
using namespace std;
void my_swap(int&, int&); //prototype
int main(){
int x = 2, y = 1;
cout << \"Before swaping in main: \" << \"x=\" << x<< \", y=\" << y << endl;
my_swap(x, y);
cout << \"After swaping in main: \" << \"x=\" << x << \", y=\" << y << endl;
return 0;
}
/*
This routine swaps the two parameters.
Because the arguments are passed by reference, the variables in caller will be swaped accordingly.
*/
void my_swap(int& a, int& b){
cout << \"Before swaping in my_swap: \" << \"a=\" << a << \", b=\" << b << endl;
int temp;
temp = b;
b = a;
a = temp;
cout << \"After swaping in my_swap: \" << \"a=\" << a << \", b=\" << b << endl;
}
