In this tutorial, we will write a program for swapping of two numbers in C++ Using functions. The swapping number can be achieved in two ways through function.
You may click on the above link to go through the call by value and call by reference in C++.
Explanation: Both of the programs take user input for the numbers to be swapped and pass it to the function as a parameter. The swapping computation is processed on the user-defined function
2. C++ Program to Swap two Numbers using Call by Value
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | #include <iostream> using namespace std; //user-defined function for swapping void swap(int x, int y) { int temp; temp = x; x = y; y = temp; cout << "\nResult after Swapping Two Numbers:\n"; cout << "num1: " << x; cout << "\nnum2: " << y; } //main function int main() { int num1, num2; cout << "Enter num1: "; cin >> num1; cout << "Enter num2: "; cin >> num2; swap(num1, num2); return 0; } |
Output:
Enter num1: 2
Enter num2: 3
Result after Swapping Two Numbers:
num1: 3
num2: 2
2. C++ Program to Swap two Numbers using Call by Reference
Since the call by reference deals with the address of the variable. Hence the use of pointer in the following program.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | #include <iostream> using namespace std; //user-defined function for swapping void swap(int *x, int *y) { int temp; temp = *x; *x = *y; *y = temp; } //main function int main() { int num1, num2; cout << "Enter num1: "; cin >> num1; cout << "Enter num2: "; cin >> num2; swap(&num1, &num2); cout << "\nResult after Swapping Two Numbers:\n"; cout << "num1: " << num1; cout << "\nnum2: " << num2; return 0; } |
Output:
Enter num1: 10
Enter num2: 20
Result after Swapping Two Numbers:
num1: 20
num2: 10
You may go through the following program in C++: