Write a C program to swap two numbers using XOR.
XOR Truth Table:
+--------------------------+
| X | Y | X xor Y |
+--------------------------+
| 0 | 0 | 0 |
| 0 | 1 | 1 |
| 1 | 0 | 1 |
| 1 | 1 | 0 |
+--------------------------+
Step 1:
num1 = num1 XOR num2
Step 2:
num2 = num1 XOR num2 (num1 is XOR of num1 and num2. See step 1)
= (num1 XOR num2) XOR num2
= num1 XOR (num2 XOR num2) // associative property (x * y) * z = x * (y * z)
= num1 XOR 0 => num1
Step 3:
num1 = num1 XOR num2 (num1 is XOR of num1 and num2. See step 1)
= (num1 XOR num2) XOR num1
= (num1 XOR num1) XOR num2
= 0 XOR num2 => num2
Hence, we swapped given two numbers.
#include <stdio.h>
int main() {
int n1, n2;
/* get two numbers from the user */
printf("Enter two numbers:");
scanf("%d%d", &n1, &n2);
/* print the given values */
printf("\nData before swapping:\n");
printf("%d\t%d\n", n1, n2);
/* swap given value */
n1 = n1 ^ n2;
n2 = n1 ^ n2;
n1 = n1 ^ n2;
/* print the swapped values */
printf("\nData After Swapping:\n");
printf("%d\t%d\n", n1, n2);
return 0;
}
XOR Truth Table:
+--------------------------+
| X | Y | X xor Y |
+--------------------------+
| 0 | 0 | 0 |
| 0 | 1 | 1 |
| 1 | 0 | 1 |
| 1 | 1 | 0 |
+--------------------------+
Step 1:
num1 = num1 XOR num2
Step 2:
num2 = num1 XOR num2 (num1 is XOR of num1 and num2. See step 1)
= (num1 XOR num2) XOR num2
= num1 XOR (num2 XOR num2) // associative property (x * y) * z = x * (y * z)
= num1 XOR 0 => num1
Step 3:
num1 = num1 XOR num2 (num1 is XOR of num1 and num2. See step 1)
= (num1 XOR num2) XOR num1
= (num1 XOR num1) XOR num2
= 0 XOR num2 => num2
Hence, we swapped given two numbers.
int main() {
int n1, n2;
/* get two numbers from the user */
printf("Enter two numbers:");
scanf("%d%d", &n1, &n2);
/* print the given values */
printf("\nData before swapping:\n");
printf("%d\t%d\n", n1, n2);
/* swap given value */
n1 = n1 ^ n2;
n2 = n1 ^ n2;
n1 = n1 ^ n2;
/* print the swapped values */
printf("\nData After Swapping:\n");
printf("%d\t%d\n", n1, n2);
return 0;
}
Output:
jp@jp-VirtualBox:~/$ ./a.out
Enter two numbers:100 200
Data before swapping:
100 200
Data After Swapping:
200 100
Enter two numbers:100 200
Data before swapping:
100 200
Data After Swapping:
200 100
No comments:
Post a Comment