Welcome to this exciting lesson on C Programming where we'll learn a fascinating trick for swapping two numbers using the XOR operator! This technique is not only fun but also super useful, especially in competitive programming. 💡
Before we dive into swapping numbers, let's first understand the XOR operator (^). XOR compares two bits and gives a true result (1) if the number of bits is odd and a false result (0) if the number of bits is even. 💡 Here's a simple truth table for XOR:
| A | B | A ^ B | | --- | --- | --- | | 0 | 0 | 0 | | 0 | 1 | 1 | | 1 | 0 | 1 | | 1 | 1 | 0 |
Now that we understand XOR, let's see how we can use it to swap two numbers. Here's a simple C function for swapping two numbers:
void swap(int a, int b) {
a = a ^ b;
b = a ^ b;
a = a ^ b;
}In this function, we're using XOR to perform a bitwise operation on the two numbers. Since XOR swaps the bits of the numbers without changing their parity, we can separate the original numbers, swap them, and then combine them back to get the swapped values. 💡
Let's break down the swap function to understand it better:
a ^ b - XORing a and b results in a new number where corresponding bits of a and b are swapped.a ^ b again - Since we have already swapped the bits, XORing the result with the original numbers will bring back the original numbers but with the swapped bits.b ^ a - This time, we XOR b and the swapped a. The result will have the swapped bits of b and the original bits of a.b ^ a again - Again, XORing the result with the original numbers will bring back the swapped numbers but with the original bits.a and b, and the swap is complete!Let's see the swap function in action:
#include <stdio.h>
void swap(int a, int b) {
a = a ^ b;
b = a ^ b;
a = a ^ b;
printf("a = %d, b = %d\n", a, b);
}
int main() {
int a = 5, b = 7;
printf("Initial values: a = %d, b = %d\n", a, b);
swap(a, b);
printf("Swapped values: a = %d, b = %d\n", a, b);
return 0;
}This program initializes two variables a and b to 5 and 7, respectively. It then calls the swap function to swap their values. After the swap, the program prints both values to verify that the swap was successful. 📝
Question: What will be the output of the given code snippet?
#include <stdio.h>
void swap(int a, int b) {
a = a ^ b;
b = a ^ b;
a = a ^ b;
printf("a = %d, b = %d\n", a, b);
}
int main() {
int a = 2, b = 3;
printf("Initial values: a = %d, b = %d\n", a, b);
swap(a, b);
printf("Swapped values: a = %d, b = %d\n", a, b);
return 0;
}A: a = 5, b = 2
B: a = 3, b = 2
C: a = 2, b = 5
Correct: B
Explanation: The XOR operator swaps the bits of the numbers without changing their parity. Since the initial values of a and b are 2 and 3, XORing them will result in a new number where corresponding bits of a and b are swapped. After the swap, assigning the swapped values back to a and b will result in the original values of b and the swapped values of a.