C++ program to swap two numbers using template function: This simple CPP tutorial code for implementing swapping concept. This source code is deals with the following,
- Swap of Numbers,
- Swap of Characters,
- Swap of two strings.
All above operations are based on the C++ template functions. There is only one class and template function. For the string swapping, we have already assigned 2 string values like Trisha and Karthikh. You can change this strings further. An example swap program is given below.
- Read: Learn English Quickly
Swap program in C++:
- Related: C program Examples & Explanation
// Header files #include<iostream.h> #include<conio.h> #include<stdio.h> template<class Swp> // Template function declaration void swap(Swp &a,Swp &b) { Swp temp; temp=k; k=z; z=temp; } void main() { int i,j; float x,y; char m,n; char *S1="TRISHA",*S2="KARTHIKH"; clrscr(); cout<<"\n \t C++ Swapping Method \n"; cout<<"\n Enter the Integer values for i & j:\n"; cin>>i>>j; cout<<" Enter the Float values for x & y:\n"; cin>>x>>y; cout<<"Enter the String values for m & n:\n"; fflush(stdin); cin>>m>>n; clrscr(); cout<<" C++ Swapping using Template function \n"; cout<<" Swap on integer values:\n"; cout<<" Before Swap operation : i is = "<<i<<"\t j = "<<j; swap(i,j); cout<<"\n After swapping Operation : i is= "<<i<<"\t j = "<<j; cout<<"\n Swap on Float values: \n"; cout<<" Before swap operation X is= "<<x<<"\t Y = "<<y; swap(x,y); cout<<"\n After swap operation: X = "<<x<<"\t Y = "<<y; cout<<"\n\ Swap on Characters : \n"; cout<<" Before swap operation M = "<<m<<"\t N = "<<n; swap(m,n); cout<<"\n After swap operation M = "<<m<<"\t N = "<<n; cout<<"\n C++ program to Swap two strings\n"; cout<<"\n Before swap operation String 1 = "<<S1<<"\t String 2 = "<<S2; swap(S1,S2); cout<<"\n After swap operation String 1 is = "<<S1<<"\t String 2 is= "<<S2; getch(); }