Problem - 2
Write a C++ program using functions to swap two values.
Solution :
#include <iostream>
#include <conio.h>
using namespace std;
void swap(int &, int &); // function prototype
int main()
{
int n,m;
cout<<"Enter your first number: ";
cin>>n;
cout<<"Enter your second number: ";
cin>>m;
cout<<"Your Numbers, Before swapping: "<<endl;
cout<<"First Number = "<<n<<endl;
cout<<"Second Number = "<<m<<endl;
swap(n,m); // function call by reference
cout<<"Your Numbers, After swapping"<<endl;
cout<<"First Number = "<<m<<endl;
cout<<"Second Number = "<<n<<endl;
getch();
return 0;
}
void swap(int &v, int &w) // function definition
{
v=v+w;
w=v-w;
v=v-w;
}
Output :
When you’ll compile this code, a console screen will pop up with a text:
Enter your first number:
After entering your first value, let’s say 169, your program will further ask you:
Enter your second number:
After you enter your second number, let’s say 29, your program will print:
Your Numbers, Before swapping
First Number = 169
Second Number = 29   
Your Numbers, After swapping
First Number = 29
Second Number = 169