• »
• Technology»
• Computers & Software»
• Computer Science & Programming

# How to Write a C Program To Swap Two Integers Using Just 2 Variables

Updated on September 25, 2013

## How it works

In this C program a user can store two integer values in two variables and the program will swap the two integer values without the help of a third variable

Eg: If a is the first variable and user gives the value 1 to it and a value 2 to b the second variable, in the output it will swap the values, that is sets a=2 and b=1. Its worked out using simple mathematical operations.

## Source Code

```#include<stdio.h>
void main()
{
int a,b;
printf("Enter value of a :");
scanf("%d",&a);
printf("Enter value of b :");
scanf("%d",&b);

a=a+b;
b=a-b;
a=a-b;

printf("\nAfter swaping the value of a=%d and b=%d ",a,b);

}```

## Further Explanation

Let 4 and 5 be the values by the user. Now the variable a holds the value 4 and variable b holds the value 5

• a=a+b (4+5=9) assigns the value 9 to a
• b=a-b (9-5=4) assigns the value 4 to b
• a=a-b (9-4=5) assigns the value 5 to a

thus the integer values has been swapped without the help of a third variable.

See results

18

2

165

7

## Popular

0 of 8192 characters used

• bethsheba david 3 years ago

please can you explain a c program to swap two variables with using third variable

• Author

Athul M R 4 years ago from Calicut, Kerala, INDIA

yup that would be another great method =)

• bfilipek 4 years ago

• aditi singh 4 years ago

thnks..

very easy to understand

keep doing

:)

• Author

Athul M R 4 years ago from Calicut, Kerala, INDIA

zaheer, positive feedback like this keeps me motivated, thank you =)

• zaheer 4 years ago

thank u.. the page is very helpful..

regards

zaheer ud din

working