Swap Two Numbers using Function in C++
Last Updated :
02 Jan, 2024
Swapping numbers means exchanging the values of the two numbers with each other. For Example,
Before Swapping:
a = 10, b = 22;
After swapping:
a = 22, b = 10
In this article, we will write a program to swap two numbers using a function in C++.
How to Swap Two Numbers Using Function in C++?
We will pass the address or reference of the two variables that we want to swap to the function. If we pass them as value, we won’t be able to change their value as in pass by value method, no changes are reflected in the original variables.
After that, we can use the temporary variable to swap the value of the given number of variables.
C++ Program for Swapping Two Numbers Using Function
C++
#include <iostream>
using namespace std;
void swap( int * a, int * b)
{
int temp = *a;
*a = *b;
*b = temp;
}
int main()
{
int a = 10;
int b = 22;
cout << "Before Swapping: " << endl;
cout << " a: " << a << " b: " << b << endl;
swap(&a, &b);
cout << "After Swapping: " << endl;
cout << " a: " << a << " b: " << b << endl;
return 0;
}
|
Output
Before Swapping:
a: 10 b: 22
After Swapping:
a: 22 b: 10
We can also make use of C++ templates to create a function that can swap the values of any kind.
C++ Program for Swapping Using Function Template
C++
#include <iostream>
#include <string>
using namespace std;
template < typename T> void swap_func(T& a, T& b)
{
T temp = a;
a = b;
b = temp;
}
int main()
{
string s1 = "Geeks" , s2 = "for" ;
int num1 = 10, num2 = 22;
cout << "Before Swapping:" << endl;
cout << s1 << " " << s2 << endl;
cout << num1 << " " << num2 << endl;
swap_func(s1, s2);
swap_func(num1, num2);
cout << "\nAfter Swapping:" << endl;
cout << s1 << " " << s2 << endl;
cout << num1 << " " << num2 << endl;
return 0;
}
|
Output
Before Swapping:
Geeks for
10 22
After Swapping:
for Geeks
22 10
Share your thoughts in the comments
Please Login to comment...