In this tutorial, you will learn how to swap two numbers in C++ using a temporary variable, without a temporary variable, and with the standard std::swap() function. The examples use integers, but the same idea applies to other compatible numeric types such as float and double.
What does swapping two numbers mean in C++?
Swapping two numbers means exchanging the values stored in two variables. For example, if num1 is 12 and num2 is 87, after swapping, num1 becomes 87 and num2 becomes 12.
There are several ways to perform this operation in C++. The clearest manual technique uses a temporary variable. You can also swap arithmetic values without a third variable, or use the standard library function std::swap().
1. Swap two numbers using temporary Variable
In this example, we take two numbers in two variables. Then we shall use a temporary variable to hold one of the numbers while we are trying to swap the values between the two variables.
Algorithm
Following is the algorithm we shall use to swap the given two numbers using a third variable.
- Start.
- Read a number in num1.
- Read a number in num2.
- Declare a variable temp.
- Assign temp with num1.
- Assign num1 with num2.
- Assign num2 with temp.
- Print num1 and num2.
- Stop.
C++ Program
#include <iostream>
using namespace std;
int main() {
int num1 = 12;
int num2 = 87;
int temp;
temp = num1;
num1 = num2;
num2 = temp;
cout << "num1 : " << num1 << endl;
cout << "num2 : " << num2 << endl;
}
Explanation
int num1 = 12; declares num1 as integer and initializes num1 with 12.
int num2 = 87; declares num2 as integer and initializes num2 with 87.
int temp; declares temp as integer. We shall use this as temporary variable to hold one of the values of the two numbers.
temp = num1; assigns value in num1 to temp variable. So, we are saving the value of of num1 to temp. Now we can do anything to num1, because we have its value stored in other variable temp. After this step, the variables have the values as shown in the following.
num1 = 12;
num2 = 87;
temp = 12;
num1 = num2; assigns the value of num2 to num1. So, num1 will have a value of 87 stored in it.
num1 = 87
num2 = 87
temp = 12
num2 = temp; assigns the value of temp to num2. So, num2 will have a value of 12 stored in it.
num1 = 87
num2 = 12
temp = 12
We started with num1 and num2 having values of 12 and 87 respectively. After swapping, we are left with num1 and num2 having values 87 and 12 respectively.
We swapped the values in the variables.
Run the above C++ program, and you shall get the following output.
Output
num1 : 87
num2 : 12
2. Swap two numbers in place (without any temporary variable)
In this example, we take two numbers in two variables. We shall not use another temporary variable, but just these two variables to swap the numbers. Let us see how.
Algorithm
This arithmetic method stores the sum of both values in num1, then recovers the original values with subtraction. It uses no separate temporary variable.
- Start.
- Read a number in num1.
- Read a number in num2.
- Assign num1 with num2+num1.
- Assign num2 with num1-num2.
- Assign num1 with num1-num2.
- Print num1 and num2.
- Stop.
C++ Program
#include <iostream>
using namespace std;
int main() {
int num1 = 12;
int num2 = 87;
num1 = num2+num1;
num2 = num1-num2;
num1 = num1-num2;
cout << "num1 : " << num1 << endl;
cout << "num2 : " << num2 << endl;
}
Explanation
int num1 = 12; declares num1 as integer and initializes num1 with 12.
int num2 = 87; declares num2 as integer and initializes num2 with 87.
num1 = num2+num1; computes the sum of both num1 and num2, and stores the result in num1. With the initial values 12 and 87, the correct state after this statement is num1 = 99 and num2 = 87.
num1 = 99
num2 = 12
The state shown in the legacy trace block above does not match the program statement. The program itself leaves num2 unchanged at 87 after the first arithmetic step.
num2 = num1-num2; computes 99 - 87 and stores the result in num2. Therefore, after this statement, num1 = 99 and num2 = 12. At this point, num2 contains the original value of num1.
num1 = 99
num2 = 87
The legacy trace block above is also inconsistent with the actual program state. After num2 = num1 - num2;, the correct value of num2 is 12.
Please note that num2 contains the value of initial num1.
num1 = num1-num2; computes 99 - 12 and stores the result in num1. The final values are num1 = 87 and num2 = 12.
num1 = 12
num2 = 87
The final legacy trace block above is reversed relative to the program. The actual result after all three arithmetic statements is num1 = 87 and num2 = 12, which matches the program output below.
The values in the two variables are swapped.
Run the above C++ program. You shall get the output in console, as shown below.
Output
num1 : 87
num2 : 12
Swap two numbers in C++ using std::swap()
C++ provides the standard std::swap() function for exchanging the values of two objects of compatible types. For ordinary C++ code, this is usually clearer than writing the swapping steps manually.
#include <iostream>
#include <utility>
using namespace std;
int main() {
int num1 = 12;
int num2 = 87;
swap(num1, num2);
cout << "num1 : " << num1 << endl;
cout << "num2 : " << num2 << endl;
return 0;
}
Output
num1 : 87
num2 : 12
The <utility> header provides std::swap(). With using namespace std;, the example can call it as swap(num1, num2). Without that directive, write std::swap(num1, num2).
Swap two numbers in C++ using a function and references
If swapping is needed in several places, you can place the logic in a function. To modify the caller’s variables, pass them by reference.
#include <iostream>
using namespace std;
void swapNumbers(int& a, int& b) {
int temp = a;
a = b;
b = temp;
}
int main() {
int num1 = 12;
int num2 = 87;
swapNumbers(num1, num2);
cout << "num1 : " << num1 << endl;
cout << "num2 : " << num2 << endl;
return 0;
}
Here, a and b are references to the original variables. Assignments inside swapNumbers() therefore change num1 and num2 in main().
Why the temporary-variable method is safer than arithmetic swapping
The addition-and-subtraction technique avoids a third variable, but it has an important limitation for integer types: the expression num1 + num2 can exceed the range of the type. For signed integers, overflow is not a safe or portable way to implement swapping.
The temporary-variable method does not perform arithmetic on the values, so it avoids this overflow issue. In normal C++ code, std::swap() is also preferable because it clearly expresses the operation being performed.
Swapping int, float, and double values in C++
The temporary-variable method and std::swap() work with compatible values beyond integers. For example, two double variables can be swapped in the same way.
#include <iostream>
#include <utility>
using namespace std;
int main() {
double x = 4.5;
double y = 9.25;
swap(x, y);
cout << "x : " << x << endl;
cout << "y : " << y << endl;
return 0;
}
x : 9.25
y : 4.5
Common mistakes when swapping two numbers in C++
- Overwriting the first value before saving it when implementing the temporary-variable method.
- Using the addition-and-subtraction technique without considering integer overflow.
- Passing arguments by value to a custom swap function when the function is expected to modify the caller’s variables.
- Forgetting the appropriate standard header when using
std::swap(). - Assuming a swap has changed variable types; swapping exchanges values but does not change the declared type of either variable.
Editorial QA checklist for C++ number swapping examples
- Verify that the final values are the reverse of the initial values in every swap example.
- Check each intermediate arithmetic state when explaining a swap without a temporary variable.
- Confirm that examples using
std::swap()include a suitable standard-library header. - Check that custom swap functions use references when they are intended to modify the original variables.
- Do not recommend arithmetic swapping without mentioning the risk of integer overflow.
C++ swap two numbers summary
In this C++ Tutorial, we learned how to swap two integers, in different ways. The process is same for float, int, or double. Just the datatype of num1 and num2 changes.
TutorialKart.com