C Program to Swap two Variables Without a Third Variable
23-09-2017
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; }
Tagged in: c interview questions