Create a function called swaps() that interchanges the values of the two arguments sent to it (pass these arguments by reference).  Make the function into a template, so it can be used with all numerical data types (char, int, float, and so on). Write a main() program to exercise the function with several types.

This answer is restricted. Please login to view the answer of this question.

Login Now
#include <iostream>
using namespace std;

template <class T>

void swaps(T &a, T &b){

    T temp = a;
    a = b;
    b = temp;
}

int main(){

    int x1, y1;
    float x2, y2;

    cout << "Enter two Integer numbers: ";
    cin >> x1;
    cin >> y1;

    cout << "Enter two Floting numbers: ";
    cin >> x2;
    cin >> y2;

    cout << "\nBefore Swap:" << endl;

    cout << "x1 = " << x1 << " y1 = " << y1 << endl;

    cout << "x2 = " << x2 << " y2 = " << y2 << endl;

    swaps(x1, y1);
    swaps(x2, y2);

    cout << "\nAfter Swap:" << endl;

    cout << "x1 = " << x1 << " y1 = " << y1 << endl;

    cout << "x2 = " << x2 << " y2 = " << y2 << endl;

    return 0;
}

The output of above program is

Enter two Integer numbers: 2
5
Enter two Floting numbers: 2.2
4.4

Before Swap:
x1 = 2 y1 = 5
x2 = 2.2 y2 = 4.4

After Swap:
x1 = 5 y1 = 2
x2 = 4.4 y2 = 2.2

 

 

If you found any type of error on the answer then please mention on the comment or report an answer or submit your new answer.
Leave your Answer:

Click here to submit your answer.

Discussion
0 Comments
  Loading . . .