Select Page

# C++ Program to Swap Two Numbers (Without using a temporary variable)

by | Jan 6, 2023 | C++, C++ Programs

## Introduction

In this program, you will learn to swap two numbers entered by the user in C++. Instead of using a third variable, we will apply addition and subtraction logic so as to swap the two numbers.

To understand this program, you should know about

1. C Data types

2. C programming operators

## Program

```#include<iostream>
using namespace std;
int main()
{
int num1, num2;
cout<<"Enter two numbers: "<<endl;
cin>>num1>>num2;

cout<<"Before swapping:\nnum1="<<num1<<"\nnum2="<<num2<<endl;
// swapping
num1=num1-num2;
num2=num1+num2;
num1=num2-num1;
cout<<"After swapping:\nnum1="<<num1<<"\nnum2="<<num2<<endl;
return 0;
}```

## Output ## Explanation

In the above program, the user is asked to enter two values.

The user enters num1=101 and num2=10.

Let’s understand the above logic

num1=num1-num2;

suppose we are assigning the subtracted value i.e., 101-10=91, to a variable num1’.

Num1’=91. Now, this is the updated value of num1’ and will be used in the further code.

num2=num1+num2;

‘num2’ is still 10 but ‘num1’ is 91 therefore we get 91+10=101. Consider num2’.

Num2’=101. Now, this is the updated value of num2’ and will be used in the further code.

num1=num2-num1;

here we will use the updated value of num1’ and num2’.

101-91=10

Therefore, the final value of num1 and num2 is 10 and 101, respectively.