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.

&temp = 10\\ \\
&a = 20

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

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

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; 

Flowchart – Swap Numbers without Third Variable

Flowchart - Swap two numbers without third variable
Figure 1 – Flowchart of Swap two numbers without third variable

Program Code – Swap Numbers without Third Variable

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

/*Program to swap two numbers without third variable */
#include <stdio.h>
#include >conio.h>
int a,b;
/* Read input */
printf("Enter value for A:");
printf("Enter value for B:");
/* Swap numbers */
a = a + b; 
b = a - b;
a = a - b;
/* Print the results */
printf("A = %d", a); printf("B = %d",b);
return 0;


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


Ads Blocker Image Powered by Code Help Pro

Ads Blocker Detected!!!

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