C Program to Swap Two Numbers | without using temporary variable & with using temporary variable

C Program to Swap Two Numbers | without using temporary variable & with using temporary variable

C Program to Swap Two Numbers

Swapping of two numbers means, first number becomes second and second number becomes first. For example, if user enters any two number say 5 and 10. And let's suppose the two variables say a and b holds these two numbers. That is, a=5 and b=10. Then after swapping it will be like a=10 and b=5.
In this example, you will learn to swap two variables by using a temporary variable and, without using a temporary variable.

C Program to Swap Two Numbers without using temporary variable:
#include<stdio.h>  
int main()    
{    
int a=5b=10;      
printf("Before swap a=%d b=%d",a,b);      
a=a+b;    
b=a-b;   
a=a-b;    
printf("\nAfter swap a=%d b=%d",a,b);    
return 0;  
}  

Output:
Before swap a= 5 b= 10
After swap a= 10 b= 5

C Program to Swap Two Numbers with using temporary variable:
#include<stdio.h>  
int main()    
{    
int a=5b=10;    
int temp;  
printf("Before swap a=%d b=%d",a,b);      
temp=a;
a=b;
b=temp
printf("\nAfter swap a=%d b=%d",a,b);    
return 0;  
}  

Output:
Before swap a= 5 b= 10
After swap a= 10 b= 5

Run Code: If you want run this code copy this code, paste here and run.

No comments: