C Program to Swap Two Numbers Without a Third Variable

Previous Article
Next Article

In many computer programs, you may need to speed up the computation process.The program will work faster if the number of steps or the number of variables are less. This program is a swapping procedure using fewer variables and also, it is a very frequently asked question in an interview or an exam.

This program is written using Dev-C++ version 4 compiler installed on a Windows 7 64-bit PC. It is intended for beginners level learners of C language.

Problem Definition

The common way to swap two given input numbers is to use a third variable in the program and hold the value of numbers temporarily.

For example

a = 10

b = 20

temp = a; /* Store the value of variable a into temp */

a = b; /* Value of b is assigned to a */

b = temp; /* Value of temp is assigned to b*/

In this program, we present a procedure to swap two given numbers without using the temp variable.



Flowchart - Program to Swap without Third Variable
Flowchart – Program to Swap without Third Variable

Program Code

/* Pragram to swap two numbers with a third variable */
#include <stdio.h>
#include <stdlib.h>
int main()
int a,b; int i;
/* Read two numbers */
printf("Enter value for A:");
printf("Enter value for B:");
/*Swap the Variales with out 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;



Output-Swap Without Third Variable
Output-Swap Without Third Variable
Previous Article
Next Article