# C Program to Swap Two Numbers Without a Third Variable

The program to swap two number uses the simple procedure with a fewer number of variables.The regular swapping procedure contains an extra variable called temp, a temporary variable to hold values in between the swap task. This program does not use any temp variable and achieve the same results.

We wrote the program with Dev-C++ version 4 compiler installed on a Windows 7 64-bit PC.  If you may try another standard C compiler, like Turbo C++ 3.0, then modify the source code according to the compiler specifications.

Learn following c programming concepts before you try this example program. If you know the concepts already, then continue reading the article.

### Problem Definition

The following code shows the common method to swap two integer numbers within a C program. As mentioned earlier, it uses a temp variable. The temp is assigned the value of variable a and a is assigned the value of variable b.

\begin{aligned}
&temp = 10\\ \\
&a = 20
\end{aligned}

In the next step, b is assigned the value of temp to complete the swap procedure.

\begin{aligned}
&b = temp;\\ \\
&b \hspace{2mm} is \hspace{2mm} 10 \hspace{2mm}now.
\end{aligned}

Code For Swap Using A Temp Variable

a = 10
b = 20
/* Store the value of variable a into temp */
temp = a;
/* Value of b is assigned to a */
a = b;
/* Value of temp is assigned to b*/
b = temp; 

### Program Code – Swap Numbers without Third Variable

/* Program to swap two numbers without a third variable */

#include <stdio.h>
#include <conio.h>
int main()
{
int a,b; int i;
printf("Enter value for A:");
scanf("%d",&a);
printf("Enter value for B:");
scanf("%d",&b);
/*Swap the Variables with out a third variable*/
a = a + b;
b = a - b;
a = a - b;
/* Print the result */
for(i=0;i<35;i++)
printf("_");printf("\n\n");
printf("A = %d B = %d\n\n",a,b);
for(i=0;i<35;i++)
printf("_");printf("\n\n");
getch();
return 0;
}

The above source code shows efficient use of arithmetic operators to swap the number and moreover, it is faster because there is no unnecessary assignments of variables.

### Output

Enter value for A:24
Enter value for B:44
----------------------------------------
A = 44 B = 24
----------------------------------------