Program to swap two numbers without temp or third variable are very important in terms of interview. In swapping we exchange the position of two numbers. There are multiple ways in which you can swap two numbers . Some of them are

Write a Program to Swap two numbers using third variable.

Swap two numbers using Bitwise XOR Operator

**Approach for Swap two Numbers without temp or third variable**

Let’s say we have two numbers a and b. We need to swap these two numbers without using any temp or third variable.

Step 1 – Add the value of a and b then assign the sum to variable a.

Step 2 – Subtract the value of variable a and b and assign it to variable b.

Step 3 – Subtract the value of variable a and b and assign it to variable a.

1 2 3 | a = a + b b = a - b a = a - b; |

Let’s check this approach. Suppose the value of a is 3 and b is 4.

1 2 3 | a = a + b = 3 + 4 = 7 // 7 is assigned b = a - b = 7 - 4 = 3 // Now the value of b is 3 a = a - b = 7 - 3 = 4 |

Now we get the output a = 4 and b = 3.

## Program to Swap Two Numbers without temp or third variable

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | <span>#include <stdio.h> #include <conio.h> </span><span>void main() { /* Declare two variables. */ int a, b; /* Take user input. */ printf("Enter two numbers a and b "); scanf("%d%d",&a,&b); </span> /* Logic to swap two numbers. */ a = a + b; b = a - b; a = a - b; printf(" Number is a = %d b = %d",a,b); getch(); } |

## PHP Code to Swap Two Numbers without temp or third Variable

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | <?php /* Initialize the value of a and b. */ $a = 4; $b = 5; function swap ($a,$b){ $a = $a + $b; $b = $a - $b; $a = $a - $b; echo "The value of a and b is". $a.' '.$b; } /* Call swap function. */ swap ($a , $b); |