In: Computer Science
C++ CODE:
#include<iostream>
#include<iomanip>
using namespace std;
// function to swap variables using reference
void swap_ref(int& n1, int& n2)
{
int temp;
temp = n1;
n1 = n2;
n2 = temp;
}
//function to swap variables using pointers
void swap_ptr(double *p,double *q)
{
double temp;
temp=*p;
*p = *q;
*q=temp;
}
int main()
{
//variable to store the input values
double x,y;
//temporary variables
double t1,t2;
// user input from the user
cout<<"Enter a floating point number: ";
cin>> x;
cout<<"\nEnter another floating point number:
";
cin>>y;
//copying the input values to temporary
variables
t1=x;
t2=y;
cout<<"\n\nSwapping the variables using
reference\n";
// the value of x and y before swapping
cout<<"\n\nBefore Swapping\n"<<endl;
cout<<"The value of x is :
"<<setprecision(2)<<fixed<<x<<endl;
cout<<"The value of y is :
"<<setprecision(2)<<fixed<<y;
//calling the function
swap(x,y);
//the value of x,y after swapping
cout<<"\n\nAfter Swapping\n"<<endl;
cout<<"The value of x is :
"<<setprecision(2)<<fixed<<x<<endl;
cout<<"The value of y is :
"<<setprecision(2)<<fixed<<y;
// reinitialize the value of x and y to user input
values
x=t1;
y=t2;
cout<<"\n\nSwapping the variables using
pointers\n";
// the value of x and y before swapping
cout<<"\nBefore Swapping\n"<<endl;
cout<<"The value of x is :
"<<setprecision(2)<<fixed<<x<<endl;
cout<<"The value of y is :
"<<setprecision(2)<<fixed<<y;
//calling the function
swap_ptr(&x,&y);
//the value of x,y after swapping
cout<<"\n\nAfter Swapping\n"<<endl;
cout<<"The value of x is :
"<<setprecision(2)<<fixed<<x<<endl;
cout<<"The value of y is :
"<<setprecision(2)<<fixed<<y;
return 0;
}
SCREENSHOT FOR OUTPUT: