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
Flowchart – Swap two numbers without third variable

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;
    /* Read two numbers */
    printf("Enter value for A:");
    printf("Enter value for B:");
    /*Swap the Variables with out a third variable*/
    a = a + b;
    b = a - b;
    a = a - b;
    /* Print the result */
    printf("A = %d B = %d\n\n",a,b);
    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.


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

Enjoy this blog? Please spread the word :)