Answer to Question #287542 in C++ for amna

Question #287542

Write a program to swap the contents of two variables. Use

template variables as function arguments.


1
Expert's answer
2022-01-14T04:36:16-0500
#include <iostream>
using namespace std;




template<typename T>
void swap(T* number1, T* number2) {
    T temp= *number1;
    *number1 = *number2;
    *number2 = temp;
}






int main() {
    // initialize variables
    int a = 1, b = 2;
    cout << "Before swapping" << endl;
    cout << "a = " << a << endl;
    cout << "b = " << b << endl;
    // call function by passing by values
    cout << "\nAfter swapping" << endl;
    
	swap<int>(&a,&b);
	cout << "a = " << a << endl;
    cout << "b = " << b << endl;




	char k = 'a', l = 'b';
    cout << "\n\nBefore swapping" << endl;
    cout << "k = " << k << endl;
    cout << "l = " << l << endl;
    // call function by passing by values
    cout << "\nAfter swapping" << endl;
    
	swap<char>(&k,&l);
	cout << "k = " << k << endl;
    cout << "l = " << l << endl;


	




	cin>>a;
    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