If you have any query feel free to chat us!
Happy Coding! Happy Learning!
In C, there are several ways to swap the values of two variables. One common way is to use a temporary variable to store one of the values, then assign the values to the variables in the correct order. Here's an example of how to swap the values of two integers using a temporary variable:
Copy code
#include <stdio.h>
void swap(int *a, int *b) {
int temp = *a;
*a = *b;
*b = temp;
}
int main() {
int x = 5, y = 10;
printf("Before swapping: x = %d, y = %d\n", x, y);
swap(&x, &y);
printf("After swapping: x = %d, y = %d\n", x, y);
return 0;
}
This method works for any type of data and it's a common and easy way to swap two variables.
Another way to swap two numbers is by using bitwise operator XOR, which is a bitwise operator that compares each bit of the first operand to the corresponding operand in the second operand. If both bits are the same, the corresponding result bit is set to 0. If both bits are different, the corresponding result bit is set to 1. Here's an example of how to swap two integers using the bitwise XOR operator:
Copy code
#include <stdio.h>
int main() {
int x = 5, y = 10;
printf("Before swapping: x = %d, y = %d\n", x, y);
x = x ^ y;
y = x ^ y;
x = x ^ y;
printf("After swapping: x = %d, y = %d\n", x, y);
return 0;
}
It's important
Comments: 0