🔁 Swapping Two Numbers Using a Temporary Variable in C++
Swapping two numbers is one of the foundational concepts in programming. In this article, we’ll explore how to swap two integers using a temporary variable in C++, along with a full example and output. We've also added a convenient "Copy Code" button for easy reuse.
💡 Definition
Swapping using a temporary variable means we use an extra variable to hold one of the values during the exchange so that no data is lost.
📄 C++ Code Example
#include <iostream>
using namespace std;
int main() {
int firstNumber, secondNumber, temp;
// Input from user
cout << "Enter the first number: ";
cin >> firstNumber;
cout << "Enter the second number: ";
cin >> secondNumber;
// Display before swapping
cout << "\nBefore Swapping:\n";
cout << "First Number = " << firstNumber << ", Second Number = " << secondNumber << endl;
// Swapping logic using a temporary variable
temp = firstNumber;
firstNumber = secondNumber;
secondNumber = temp;
// Display after swapping
cout << "\nAfter Swapping:\n";
cout << "First Number = " << firstNumber << ", Second Number = " << secondNumber << endl;
return 0;
}
🛠️ How to Use
-
Copy the above code using the 📋 Copy Code button.
-
Paste it into a
.cpp
file, for example:SwapExample.cpp
. -
Compile using any C++ compiler:
g++ SwapExample.cpp -o SwapExample
-
Run the program:
./SwapExample
📌 Sample Output
Enter the first number: 15
Enter the second number: 25
Before Swapping:
First Number = 15, Second Number = 25
After Swapping:
First Number = 25, Second Number = 15
Post a Comment