swapping of two numbers in c without temporary variable
Swapping Two Numbers in C without a Temporary Variable
To swap two numbers in C without using a temporary variable, you can use the XOR bitwise operator. Here are the steps to perform the swap:
Initialize the two numbers: Start by initializing the two numbers that you want to swap. Let's call them
a
andb
.Perform the swap: Use the XOR bitwise operator to swap the values of
a
andb
. The XOR operator (^
) returns 1 if the corresponding bits of its operands are different, and 0 if they are the same. By performing the XOR operation twice, you can effectively swap the values ofa
andb
without using a temporary variable.
c
a = a ^ b;
b = a ^ b;
a = a ^ b;
The XOR operation works as follows:
- a = a ^ b
sets a
to the bitwise XOR of a
and b
. This effectively stores the combined value of a
and b
in a
.
- b = a ^ b
sets b
to the bitwise XOR of the new value of a
(which is the combined value of a
and b
) and the original value of b
. This effectively stores the original value of a
in b
.
- a = a ^ b
sets a
to the bitwise XOR of the new value of a
(which is the combined value of a
and b
) and the new value of b
(which is the original value of a
). This effectively stores the original value of b
in a
.
- Verify the swap: After performing the swap, you can verify that the values of
a
andb
have been successfully swapped.
c
printf("After swapping:\n");
printf("a = %d\n", a);
printf("b = %d\n", b);
This will print the values of a
and b
after the swap.
Here's the complete code:
#include <stdio.h>
int main() {
int a, b;
// Step 1: Initialize the two numbers
a = 10;
b = 20;
// Step 2: Perform the swap
a = a ^ b;
b = a ^ b;
a = a ^ b;
// Step 3: Verify the swap
printf("After swapping:\n");
printf("a = %d\n", a);
printf("b = %d\n", b);
return 0;
}
When you run this code, it will output:
After swapping:
a = 20
b = 10
This confirms that the values of a
and b
have been successfully swapped.