C++ Program to Swap Two Variables Using Third Variable

C++ program to swap two numbers using third variable can be implemented by using another variable apart from the variables which store the two given numbers. Swapping of two numbers means the exchanging of values between them.






1. C++ Program & output of to Swap Two Numbers using Third Variable

Code has been copied
/********************************
    alphabetacoder.com
 C++ program to swap two numbers 
 using third variable
*********************************/
#include <iostream>

using namespace std;

int main() {
    int num1, num2, temp;
    // take input of the numbers
    cout << "Enter two numbers = ";
    cin >> num1;
    cin >> num2;
    cout << "Before swapping: number1 = " << num1 << " and number2 = " << num2 << "\n";

    //do swapping operation  using temp
    temp = num1;
    num1 = num2;
    num2 = temp;

    // display result
    cout << "After swapping: number1 = " << num1 << " and number2 = " << num2 << "\n";

    return 0;
}

Output


Enter two numbers = 5 10

Before swapping: number1 = 5 and number2 = 10

After swapping: number1 = 10 and number2 = 5