There are several ways to swap the values of two variables without using a third variable. Here are some commonly used methods:
Using a third variable: This is the most straightforward approach where you use a temporary variable to store the value of one variable, then assign the value of the second variable to the first variable, and finally assign the value of the temporary variable to the second variable.
Using arithmetic operations: You can use addition and subtraction operations to swap the values. This method involves adding one variable to the other, assigning the result to one variable, and then subtracting the original value of the second variable to assign it to the first variable.
Using bitwise XOR: XOR (^) operation can be used to swap two values without using a third variable. It works by exploiting the property of XOR that when two different bits are XORed, the result is 1, and when two same bits are XORed, the result is 0.
Using multiplication and division: You can multiply one variable by the other, assign the result to one variable, and then divide the result by the original value of the second variable to assign it to the first variable.
Using bitwise operations: Bitwise operations such as left shift (<<) and right shift (>>) can be used to swap values by manipulating the individual bits of the variables.
a = a ^ b; b = a ^ b; a = a ^ b;
a = a + b; b = a - b; a = a - b;
a = a - b; b = a + b; a = b - a;
a= a*b; b=a/b; a=a/b
a = a ^ b; b = a ^ b; a = a ^ b;
No comments:
Post a Comment