How to Swap Two Numbers in C without Using Third Variable.
Follow these 3 methods :
Write C program to swap two numbers using
- + and – operators.
- * and / operators.
- XOR operator.
Test Case: a=10 and b=40
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
How to swap two numbers in C without a third variable using XOR operator
a = a ^ b // a = 100010 b = a ^ b // b = 1010 a = a ^ b // a = 101000
a = 34 b = 10 a = 40
Swapping Code:
Pros and cons of using XOR operator to swap two numbers in C
XOR operator is a bitwise operation that returns 1 if the bits are different and 0 if they are the same.
It can be used to swap two numbers by toggling their bits without using a third variable.
Here are some of the benefits and drawbacks of this technique:
Benefits
Drawbacks
C program using * and / operators to swap two numbers without using a third variable
C program using + and – operators to swap two numbers without using a third variable
#include<stdio.h> int main() { int a = 10, b = 40; printf("Before swap: a = %d ; b = %d\n", a, b); a = a + b; // a = 50 b = a - b; // b = 10 a = a - b; // a = 40 printf("After swap: a = %d ; b = %d\n", a, b); return 0; }