Write a C++ program to swap two numbers. The first program uses temporary variable to swap numbers, whereas the second program doesn’t use temporary variables.
Example 1: Swap Numbers (Using Temporary Variable)
C++ Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
#include <iostream> using namespace std; int main() { int a = 5, b = 10, temp; cout << "Before swapping." << endl; cout << "a = " << a << ", b = " << b << endl; temp = a; a = b; b = temp; cout << "\nAfter swapping." << endl; cout << "a = " << a << ", b = " << b << endl; return 0; } |
Example 2: Swap Numbers Without Using Temporary Variables
C++ Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
#include <iostream> using namespace std; int main() { int a = 5, b = 10; cout << "Before swapping." << endl; cout << "a = " << a << ", b = " << b << endl; a = a + b; b = a - b; a = a - b; cout << "\nAfter swapping." << endl; cout << "a = " << a << ", b = " << b << endl; return 0; } |
Output: