Write a C++ Program to Swap Two Numbers.

This program declares two variables num1 and num2 to hold the two numbers entered by the user. It then uses the cin object to read the numbers from the standard input stream and the cout object to print the numbers before and after swapping.

To swap the two numbers, the program uses a temporary variable temp to store the value of num1, and then assigns the value of num2 to num1 and the value of temp (which is the original value of num1) to num2. This effectively swaps the two numbers.

I hope this helps! Let me know if you have any questions.

#include <iostream>

using namespace std;

int main()
{
    int num1, num2; // Declare variables to hold the two numbers

    cout << "Enter the first number: "; // Prompt the user to enter the first number
    cin >> num1; // Read the first number from the standard input stream

    cout << "Enter the second number: "; // Prompt the user to enter the second number
    cin >> num2; // Read the second number from the standard input stream

    cout << "Before swapping: num1 = " << num1 << ", num2 = " << num2 << endl; // Print the numbers before swapping

    // Swap the two numbers using a temporary variable
    int temp = num1;
    num1 = num2;
    num2 = temp;

    cout << "After swapping: num1 = " << num1 << ", num2 = " << num2 << endl; // Print the numbers after swapping

    return 0;
}

Here is a line-by-line explanation of the C++ program to swap two numbers:

Copy code

#inlcude

This line includes the iostream header file, which provides input and output streams (cin and cout, respectively) that can be used to read from and write to the standard input and output streams.

Copy code
using namespace std;

This line includes the using namespace std directive, which allows you to use the names of the functions and objects in the std namespace (such as cin and cout) without specifying the namespace prefix std::.

Copy code
int main()
{
int num1, num2; // Declare variables to hold the two numbers

This line declares the main function, which is the entry point of every C++ program. It is where the program begins execution. The line also declares two variables num1 and num2 of type int to hold the two numbers entered by the user.

Copy code
cout << “Enter the first number: “; // Prompt the user to enter the first number cin >> num1; // Read the first number from the standard input stream

These lines use the cout object to print a prompt asking the user to enter the first number, and the cin object to read the number from the standard input stream and store it in the num1 variable