Home >>c programs >C Program to swap two numbers

C Program to swap two numbers

Write a Program to Swap Two Numbers in C without third Variable

Swapping two number in C programming language defines the exchange values of two variables. Let’s suppose you have two variable X & Y. Value of X is 15 & value of Y is 25. So, after swapping the value, X will become 25 & Y will become 15.

Program to swap two numbers without third variable

You can swap two numbers without using third variable

Let's take an example

#include<stdio.h>  
 int main()    
{    
int x=10, y=20;      
printf("Before swaped number  x=%d y=%d",x,y);      
x=x+y;//a=30 (10+20)    
y=x-y;//y=10 (30-20)    
x=x-y;//x=20 (30-10)    
printf("\nAfter swaped Number  x=%d y=%d",x,y);    
return 0;  
}   
Output :
Before swaped number x=10 y=20
After swaped Number x=20 y=10

C Program to swap two numbers using third variable

#include<stdio.h>  
int main()    
{    
int x=10, y=20,z=0;      
printf("Before swaped number  x=%d y=%d",x,y);      
z=x;
x=y;
y=z;
printf("\nAfter swaped Number  x=%d y=%d",x,y);    
return 0;  
}   
Output :
Before swaped number x=10 y=20
After swaped Number x=20 y=10

Popular Tutorials