Write a program to swap two numbers in C++

C++ program to swap two numbers using a temporary variable:https://www.highrevenuegate.com/thv230z41?key=45186ab3250d84bc139c728d674b7281

C++

The first step is to define two variables, x and y. We then assign the value 10 to x and the value 20 to y.

Next, we use a temporary variable to swap the values of x and y. We do this by first assigning the value of x to the temporary variable. We then assign the value of y to x. Finally, we assign the value of the temporary variable to y.

The last step is to print the values of x and y. After swapping the values, x will now contain the value 20 and y will now contain the value 10.

Here is a diagram that illustrates how the swap works:

Before:

x = 10
y = 20

After:

x = 20
y = 10
#include <iostream>

using namespace std;

int main() {
  int a = 10, b = 20;

  // Using a temporary variable
  int temp = a;
  a = b;
  b = temp;

  cout << "a = " << a << endl;
  cout << "b = " << b << endl;

  return 0;
}

Here’s a program in C++ that swaps the values of two numbers:





#include <iostream>

void swap(int& a, int& b) {
    int temp = a;
    a = b;
    b = temp;
}

int main() {
    int num1 = 5;
    int num2 = 10;

    std::cout << "Before swapping: num1 = " << num1 << ", num2 = " << num2 << std::endl;

    swap(num1, num2);

    std::cout << "After swapping: num1 = " << num1 << ", num2 = " << num2 << std::endl;

    return 0;
}
Scroll to Top