Write a program to swap two numbers in C++

 #include <iostream>


using namespace std;


int main() {

    int num1, num2, temp;


    cout << "Enter two numbers: ";

    cin >> num1 >> num2;


    // swap numbers using temporary variable

    temp = num1;

    num1 = num2;

    num2 = temp;


    cout << "After swapping, the numbers are " << num1 << " and " << num2 << endl;


    return 0;

}

In this program, we declare three integer variables num1, num2, and temp. We prompt the user to enter two numbers and read them into num1 and num2.

To swap the two numbers, we use a temporary variable temp. We store the value of num1 in temp, then assign the value of num2 to num1, and finally assign the value of temp to num2. This effectively swaps the values of the two variables.

We then print out the new values of num1 and num2 to verify that the swap was successful. Finally, we return 0 to indicate successful execution of the program.


Post a Comment

0 Comments