Function template
Aim:To write a C++ program to swap two variables using function template.
Algorithm:
Step 1: Declare the template to perform swap operation.
Step 2: In the main, get the values for integer data type
2.1 Call the swap function.
2.2 Display the swapped values.
Step 3: Get the values for float data type
3.1 Call the swap function.
3.2 Display the swapped values.
Step 4: Get the values for character data type
4.1 Call the swap function.
4.2 Display the swapped values.
Program:
#include<iostream.h>
#include<conio.h>
template<class T>
void swap(T &x,T &y)
{
T t;
t=x;
x=y;
y=t;
}
void main()
{
clrscr();
int a,b;
cout<<"\nENTER THE INTEGER VALUES:\n";
cin>>a>>b;
swap(a,b);
cout<<"\nTHE SWAPPED VALUES ARE:"<<a<<"\t"<<b;
float c,d;
cout<<"\n\nENTER THE FLOAT VALUES:\n";
cin>>c>>d;
swap(c,d);
cout<<"\n THE SWAPPED VALUES ARE:"<<c<<"\t"<<d;
char ch1,ch2;
cout<<"\n\nENTER THE CHARACTER VALUES:\n";
cin>>ch1>>ch2;
swap(ch1,ch2);
cout<<"\n THE SWAPPED VALUES ARE:"<<ch1<<"\t"<<ch2;
getch();
}
Output:
ENTER THE INTEGER VALUES: 67 12
THE SWAPPED VALUES ARE: 12 67
ENTER THE FLOAT VALUES: 8.9 1.2
THE SWAPPED VALUES ARE: 1.2 8.9
ENTER THE CHARACTER VALUES: r a
THE SWAPPED VALUES ARE: a r
0 comments:
Post a Comment