Answer to Question #185661 in C++ for VASANTH V

Question #185661

Design a template function for swapping the int, double and char type values between two variables. Note: Use function overloading.


1
Expert's answer
2021-04-27T14:54:22-0400
#include <iostream>
using namespace std;

template <class T>
void SWAP_T(T& first, T& second)
{
	T temp(first);
	first = second;
	second = temp;
}

void SWAP(int& i, int& j)
{
	int temp = i;
	i = j;
	j = temp;
}


void SWAP(double& i, double& j)
{
	double temp = i;
	i = j;
	j = temp;
}


void SWAP(char& i, char& j)
{
	char temp = i;
	i = j;
	j = temp;
}


int main()
{
	int a = 10;
	int b = 20;
	cout << a << " " << b << endl;
	cout << "SWAP()" << endl;
	SWAP(a, b);
	cout << a << " " << b << endl << endl;


	double c = 10.5;
	double d = 200.6;
	cout << c << " " << d << endl;
	cout << "SWAP()" << endl;
	SWAP(c, d);
	cout << c << " " << d << endl << endl;


	char e = 'e';
	char f = 'f';
	cout << e << " " << f << endl;
	cout << "SWAP()" << endl;
	SWAP(e, f);
	cout << e << " " << f << endl << endl;
	return 0;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS