Program to swap two number

0 Suresh Chand March 28, 2021

In this article, we will learn how to swap two numbers using the C++ programming language.

We will do this using two technique.

  • Method 1: Using Temporary variable
  • Method 2: Without using Temporary variable

Example 1: Swap Two using Temporary variables

In this example, We will use the temporary variable to swap two numbers. We will three variables to swap numbers.

We will do this using following steps:

  • Step 1: Assign value of first variable to temporary variable
  • Step 2: Assign second variable value to first variable
  • Step 3: Assign Temporary variable value to second variable
#include <iostream>
using namespace std;

int main()
{
    int a = 10, b = 20, 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;
}

The output of above program is

Before swapping : 
a = 10, b = 20

After swapping : 
a = 20, b = 10

Example 2 : Swap two number without temporary variable

In this example, We will swap two numbers without using the temporary variable.

We will do this using following steps:

  • Step 1: Initially Declare variables and assign values
  • Step 2: Add two variables and assign to first variable
  • Step 3: We will subtract second variable from first variable and assign to second variable
  • Step 4: Subtract second variable from first variable and assign to first variable

Let look on visual view

a = 10, b = 20

a = a + b   // value = 30
b = a - b  // Value = 30 - 20 = 10
a = a - b // Value = 30 - 10 = 20

//output
a = 20 and b = 10

We cannot use multiplication and division here instead of addition. Let’s look on full code to make more clear on this program.

#include <iostream>
using namespace std;

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

    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;
}

The output of this program is same as above program.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

Join Our Newsletter Now

Get the latest tutorials, examples and projects updates.

Ads Block Detector Powered by codehelppro.com

Ads Blocker Detected!!!

We have detected that you are using extensions to block ads. Please support us by disabling these ads blocker.

Disable Ad Block

Want Same System