Showing posts with label Three Methods of swapping. Show all posts
Showing posts with label Three Methods of swapping. Show all posts

Three Methods of swapping

Three Methods of C++ and C that would swap the 2 number.

Method 1:

Step 1 : a=a+b;
Step 2 : b = a-b;
Step 3 : a= a-b;

Example num1=5;num2=2;

Step 1 : num1 = (5+2) = 7
Step 2 : num2 =(7-2) = 5;
Step 3 : num1 = (7-5)= 2 ;

finally num1=2;num2=5;


Method 2 :
num2 = (num1*num1)/num1 + (num1=num2) - num1


Method 3:
num1^=num2^=num1^=num2;

try it!