Swapping the values of two variables is a common task in programming. While the traditional approach involves using a third variable, today we will explore two alternative algorithms in C that allow us to achieve the same result without the need for that extra variable.
Program 1: Addition and Subtraction:
The first algorithm utilizes addition and subtraction to accomplish the swap. Here’s how it works:
#include <stdio.h>
void swap(int* a, int* b)
{
*a = *a + *b; // Step 1: Add both numbers and store the sum in *a
*b = *a - *b; // Step 2: Subtract the original value of *b from the sum and store the result in *b
*a = *a - *b; // Step 3: Subtract the original value of *a from the sum and store the result in *a
}
int main()
{
int x = 5;
int y = 10;
printf("Before swapping: x = %d, y = %d\n", x, y);
swap(&x, &y); // Pass the addresses of x and y
printf("After swapping: x = %d, y = %d\n", x, y);
return 0;
}
By adding the values of the variables and then subtracting them, we effectively interchange their values. This technique is straightforward and doesn’t rely on any additional libraries or complex operations.
Program 2: Bitwise XOR with Assignment Operator:
The second algorithm takes advantage of the XOR (exclusive OR) operation and the assignment operator to perform the swap. Here’s the code:
#include <stdio.h>
void swap(int* a, int* b)
{
*a ^= *b; // Step 1: Perform bitwise XOR and store the result in *a
*b ^= *a; // Step 2: Perform bitwise XOR between the updated value of *a and *b, and store the result in *b
*a ^= *b; // Step 3: Perform bitwise XOR between the updated value of *a and *b, and store the result in *a
}
int main()
{
int x = 5;
int y = 10;
printf("Before swapping: x = %d, y = %d\n", x, y);
swap(&x, &y); // Pass the addresses of x and y
printf("After swapping: x = %d, y = %d\n", x, y);
return 0;
}
Using bitwise XOR, we manipulate the individual bits of the variables to achieve the desired swap. The XOR operation allows us to combine the bits without losing any information. This method is particularly intriguing due to its elegance and efficiency.
Feel free to give it a try and let me know your thoughts! If you have any questions or alternative approaches, I’d love to hear from you. Let’s continue to explore the exciting world of algorithms and programming together! 🤝
Leave a comment