In: Computer Science
For C++
Make a function that swaps the values that change the values between the parameters as the following rule.
The functions swap takes 2, 3 or 4 parameters and these functions are implemented as the overloading functions.
#include <iostream>
using namespace std;
void swap(int &a, int &b) {
// Switching the given variables with the help of a temporary variable.
int temp = a;
a = b;
b = temp;
}
void swap(int &a, int &b, int &c) {
int mini, medi, maxi;
// Finding the smallest, intermediate and largest element.
if (a > b && a > c) {
maxi = a; // A will be the largest number.
// The ternary operator first checks the condition
// If the condition is true, the code before the colon (:) gets into the consideration
medi = (b>c ? b : c); // Since a is already the largest, if b > c, then b will be the second largest
mini = (b > c ? c : b); // Similarly this operates
}
// Similarly the below cases operate.
else if (b > c) {
maxi = b;
medi = (a > c ? a : c);
mini = (a > c ? c : a);
}
else {
maxi = c;
medi = (a > b ? a : b);
mini = (a > b ? b : a);
}
a = mini;
b = medi;
c = maxi;
}
void swap(int &a, int &b, int &c, int &d) {
// Switching the elements one by one.
int temp = a;
a = b;
b = c;
c = d;
d = temp;
}
int main() {
// Call the main as per the requirement.
}
The above program has three overloading swap functions, first one takes two parameters , second takes three parameters and third takes four parameters.