C++ program to swap two variable using template function
Today i am going to swap to variable's contents using template function. The below is the C++ program that swap two variable's contents.
// C++ program to swap two variable contants
// Using template function
#include<iostream>
using namespace std;
template <typename t> // defining template function
void swap(t *var,t *var1){
t var2;
var2=*var; //swaping the contents
*var=*var1;
*var1=var2;
}
int main(){
// displaying the menu to the user
cout<<"1. Swap two integer numbers:";
cout<<"\n2. Swap two float numbers:";
cout<<"\n3. Swap two characters:";
cout<<"\n Enter your choice:";
short i;
cin>>i; // storing the choice of the user
switch(i){
case 1:
{
int a,b;
cout<<"\n Enter 1st numbers:";
cin>>a;
cout<<"\n Enter 2nd number:";
cin>>b;
cout<<"Before swap:\n a="<<a<<" b="<<b;
swap(&a,&b); // calling template function
cout<<"\nAfter swap:\n a="<<a<<" b="<<b;
break;
}
case 2:
{
float a,b;
cout<<"\n Enter 1st float number:";
cin>>a;
cout<<"\n Enter 2st float number:";
cin>>b;
cout<<"Before swap:\n a="<<a<<" b="<<b;
swap(&a,&b); // calling template function
cout<<"\nAfter swap:\n a="<<a<<" b="<<b;
break;
}
case 3:
{
char a,b;
cout<<"\n Enter 1st character:";
cin>>a;
cout<<"\n Enter 2st character:";
cin>>b;
cout<<"Before swap:\n a="<<a<<" b="<<b;
swap(&a,&b); // calling template function
cout<<"\nAfter swap:\n a="<<a<<" b="<<b;
break;
}
default:
cout<<"\n Invalid choice!!! Try again:";
main(); // asking to the user to re-enter his/her choice
}
}
Output :-
The output of the above program is:
When user enter his or her choice 1, then the out put will be:
When user enter his or her choice 2, then the output will be :
When user enter his or her choice 3, then the out put will be:
Dear visitors, drop your questions (if any) on the comment section, i will answer your questions. If you have any doubts please comment me, i will try to solve your doubts. Thanks for visiting.
Comments
Post a Comment