Write a function template to swap the numbers.
Sep 23, 2018Program Source Code:
#include<iostream> using namespace std; // defining the function template that // swaps two numbers // here we use pass by reference concept template <class T> void swapthem(T &t1, T &t2){ T temp; temp = t1; t1 = t2; t2 = temp; } int main(){ int num1 = 20, num2 = 50; cout<<"Before swap:"<<endl; cout<<"num1 = "<<num1<<" and num2 = "<<num2<<endl; swapthem(num1, num2); cout<<"After swap:"<<endl; cout<<"num1 = "<<num1<<" and num2 = "<<num2<<endl; return 0; }
Sample Run:
Before swap: num1 = 20 and num2 = 50 After swap: num1 = 50 and num2 = 20