Swapping of 2 Numbers Program in C

This Swapping of 2 Numbers Program in C Language post explains clearly how to swap two numbers in different ways like using a temporary variable, without using a temporary variable and by using XOR operator.


Swapping of 2 numbers using temp variable :
#include<stdio.h>
void main()
{
int x=10 , y=20 , temp ;
temp = x ;
x = y ;
y = temp ;
printf(“x : %d \t y : %d”,x,y);
}


Swapping 2 numbers without using temp variable:
#include<stdio.h>
void main()
{
int x=10 , y=20 ;
x = x+y ;
y = x-y ;
x = x-y ;
printf(“x : %d \t y : %d”,x,y);
}


Swapping 2 numbers using XOR operator:
#include<stdio.h>
void main()
{
int x=10 , y=20 ;
x = x^y ;
y = y^x ;
x = x^y ;
printf(“x : %d \t y : %d”,x,y);
}


 

Share this