Summary: In this programming example, we will swap two numbers in C++ using call by reference and call by address.
Swap Numbers by Call by Reference
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 | #include <iostream> using namespace std; void swapByReference(int &m, int &n){ int temp= m; m=n; n=temp; } int main() { int a,b; cout << "Enter two numbers A & B"<< endl; cin >> a; cin >> b; cout << "Value of A before swapping: " << a <<endl; cout << "Value of B before swapping: " << b <<endl; swapByReference(a,b); cout << "Value of A after swapping: " << a <<endl; cout << "Value of B after swapping: " << b <<endl; } |
Output:
Enter two numbers A & B5 3
Value of A before swapping: 5
Value of B before swapping: 3
Value of A after swapping: 3
Value of B after swapping: 5
In this example, we are passing the reference of a and b to the swapByReference
method for the swapping process.
In the swapByReference
method, we interchange the reference of the two variables using a temporary variable.
Swap Numbers by Call by Address
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 | #include <iostream> using namespace std; void swapUsingAddress(int *m, int *n){ int temp= *m; *m=*n; *n=temp; } int main() { int a,b; cout << "Enter two numbers A & B"<< endl; cin >> a; cin >> b; cout << "Value of A before swapping: " << a <<endl; cout << "Value of B before swapping: " << b <<endl; //passing address of a and b swapUsingAddress(&a, &b); cout << "Value of A after swapping: " << a <<endl; cout << "Value of B after swapping: " << b <<endl; } |
Output:
Enter two numbers A & B9 5
Value of A before swapping: 9
Value of B before swapping: 5
Value of A after swapping: 5
Value of B after swapping: 9
In this method, we have used pointers to interchange the values of a and b.
Instead of value or reference, we pass the address of variables a and b to the swapUsingAddress
method and swap their values by dereferencing the same.
Hope now you know, how to swap two numbers using reference and address in C++. If you have any doubts about the tutorial then comment below.