Home About Contact Privacy Terms Disclaimer
TECHAntena
Last Updated On: September 23, 2017
Editor: Adeeb C

C Program to Swap two Variables Without a Third Variable

Category: C,Programing
Tags

In many cases, we swap variables with help of a temp or third variable. Here is the C program to swap two variables without using a third variable.

Swapping two variables by no using the third variable is a common question in C interview questions.

C Program to Swap two Variables Without a Third Variable

#include<stdio.h>
int main(){
int a=5,b=10;
//step one
a=b+a;
b=a-b;
a=a-b;
printf("a= %d b= %d",a,b);
//step two
a=5;
b=10;
a=a+b-(b=a);
printf("\na= %d b= %d",a,b);
//step three
a=5;
b=10;
a=a^b;
b=a^b;
a=b^a;
printf("\na= %d b= %d",a,b);
//step four
a=5;
b=10;
a=b-~a-1;
b=a+~b+1;
a=a+~b+1;
printf("\na= %d b= %d",a,b);
//step five
a=5,
b=10;
a=b+a,b=a-b,a=a-b;
printf("\na= %d b= %d",a,b);
return 0;
}