Swapping two numbers in C++ involves the use of a temporary variable to store one of the numbers, so that you can safely change the values of the original variables. Below is a simple C++ program written for Turbo C++ to swap two numbers.
#include <iostream.h>
#include <conio.h>
void main() {
clrscr(); // Clear the screen (specific to Turbo C++)
int num1, num2, temp;
cout << "Enter first number: ";
cin >> num1;
cout << "Enter second number: ";
cin >> num2;
// Swapping logic using a temporary variable
temp = num1;
num1 = num2;
num2 = temp;
cout << "After swapping: " << endl;
cout << "First number: " << num1 << endl;
cout << "Second number: " << num2 << endl;
getch(); // Wait for user input (specific to Turbo C++)
}
To compile and run the program in Turbo C++:
- Open Turbo C++.
- Create a new file and copy-paste the above code into it.
- Save the file.
- Compile the code (usually by pressing Alt + F9).
- Run the program (usually by pressing Ctrl + F9).
You’ll be prompted to enter two numbers. After entering them, the program will display the numbers after swapping.
