Q9. Write a code to swap two numbers without using temporary variable

Solution : We can swap two numbers without using temporary variable. By using + and – operator we can swap two number.

Swapping two number :- Swap two numbers means exchange the values of two variables with each other.
For example:
Before Swapping : num1 = 30 and num2 = 25.
After Swapping : num1 = 25 and num2 = 30.

Logic :- Suppose we are given 2 numbers num1 = 30 and num2 = 25 and we have to swap these 2 numbers without using third variable. Then we have to perform below operations to swap the numbers.

1. Firstly we will add both the number and will assign to the first number.
num1 = num1 + num2
num1 = 30 + 25=45

2. Secondly we will subtract second number from the first number (updated value after step 1)
num2 = num1 – num2
num2 = 45 – 25
num2 = 30

3. Third step will be subtracting second number (updated value after step 2) from the first number (updated value from step 1)
num1 = num1 – num2
num1 = 45 – 30
num1 = 25

After the above 3 steps we will get our required result i.e we have swapped 2 numbers without using third variable.

There is Following Algorithm to swap two numbers without using third variable

//Algorithm To Swap Two Numbers Without Using Temporary Variable
START
Step 1 -> Take two integer as input num1 and num2.
Step 2 -> Print number before swapping
Step 3 -> num1 = num1 + num2;
Step 4 -> num2 = num1 – num2;
Step 5 -> num1 = num1 – num2;
Step 6 -> Print numbers after swapping
STOP

There is Following code to swap two numbers without using third variable

Output

Enter Two Numbers :
30,25
Number before swapping is 30 and 25
Number after swapping is 25 and 30

Recommended Programs
Program to find factorial of a number
Program to count number of digits in a number