Let’s assume a, b two numbers, there are a lot of methods two swap two numbers without using the third variable.
Method 1( (Using Arithmetic Operators):
#include <stdio.h>
int main()
{
int a = 10, b = 5;
// algo to swap 'a' and 'b'
a = a + b; // a becomes 15
b = a - b; // b becomes 10
a = a - b; // fonally a becomes 5
printf("After Swapping the value of: a = %d, b = %d\n\n", a, b);
return 0;
}
Method 2 (Using Bitwise XOR Operator):
#include <stdio.h>
int main()
{
int a = 10, b = 5;
// algo to swap 'a' and 'b'
a = a ^ b; // a becomes (a ^ b)
b = a ^ b; // b = (a ^ b ^ b), b becomes a
a = a ^ b; // a = (a ^ b ^ a), a becomes b
printf("After Swapping the value of: a = %d, b = %d\n\n", a, b);
return 0;
}
Answer:
Let’s assume a, b two numbers, there are a lot of methods two swap two numbers without using the third variable.
Method 1( (Using Arithmetic Operators):
Method 2 (Using Bitwise XOR Operator):
need an explanation for this answer? contact us directly to get an explanation for this answer