Let the two variables be 'a' and 'b'.

Method 1: Sum and difference

a=a+b;

b=a-b;

a=a-b;

Method 2: Product and division

a=a*b;

b=a/b;

a=a/b;

Method 3: Three successive bitwise XORs

a=a XOR b;

b=a XOR b;

a=a XOR b;

Method 4: One liner code with double assignment

b=a-b+(a=b);

And here is the C implementation of all the given methods

#include <stdio.h>

#include <process.h>

int main(){

int a, b, c;

printf("Enter the value of 'a':\n");

scanf("%d", &a);

printf("Enter the value of 'b':\n");

scanf("%d", &b);

printf("Enter the method for swapping the values:\n1 for sum method, 2 for product method, 3 for XOR method, 4 for one liner method, anything else to exit.\n");

scanf("%d", &c);

switch(c){

case 1:

a=a+b;

b=a-b;

a=a-b;

printf("You chose method 1. The new values are a=%d and b=%d\nThe algorithm used was:\na=a+b;\nb=a-b;\na=a-b;",a,b);

break;

case 2:

a=a*b;

b=a/b;

a=a/b;

printf("You chose method 2. The new values are a=%d and b=%d\nThe algorithm used was:\na=a*b;\nb=a/b;\na=a/b;",a,b);

break;

case 3:

a=a^b;

b=a^b;

a=a^b;

printf("You chose method 3. The new values are a=%d and b=%d\nThe algorithm used was:\na=a XOR b;\nb=a XOR b;\na=a XOR b;",a,b);

break;

case 4:

b=a-b+(a=b);

printf("You chose method 4. The new values are a=%d and b=%d\nThe algorithm used was: b=a-b+(a=b);",a,b);

break;

default:

exit(0);

}

return (0);

}

The third and the fourth methods are geekier than the previous two. I leave it to you to find out how the third method works.

## 1 comment:

desidude03.blogspot.com visit it...relli lykd your Bro!!!!!!!!

Post a Comment