1.

Swap the values of two variables, x and y, without needing a third variable.

Answer»
  • Approach 1:

The goal is to find a sum in one of the two numbers provided. The total and subtraction from the sum can then be used to SWAP the INTEGERS.

Code:

#include <bits/stdc++.h>using namespace std;int main(){ int a = 1, b = 2; cout << "Before Swapping : a = " << a << " and b = " << b << "\n"; a = a + b; // storing the sum of a and b in a b = a - b; // storing the value of the original a in b a = a - b; // storing the value of the original b in a cout << "After Swapping : a = " << a << " and b = " << b << "\n";}

OUTPUT :

Before Swapping : a = 1 and b = 2After Swapping : a = 2 and b = 1

Explanation :
In the above code, we first stored the sum of both the numbers in the first variable. Then, we store the original value of the first variable in the second variable by subtracting the second variable from the sum. Similarly we CHANGE the value for the second variable as well. Thus, we SWAPPED the two numbers without using a third variable.

  • Approach 2 :

To swap two variables, use the bitwise XOR operator. When two integers x and y are XORed, the result is a number with all bits set to 1 wherever the bits of x and y differ. For instance, the XOR of 10 (in Binary 1010) and 5 (in Binary 0101) is 1111, while the XOR of 7 (0111) and 5 (0101) is 1111. (0010). We can then xor the resultant XORed with the other number to swap the values. Considering the above example, when we xor 1111 with 0101 we get 1010.

Code :

#include <bits/stdc++.h>using namespace std;int main(){ int a = 1, b = 2; cout << "Before Swapping : a = " << a << " and b = " << b << "\n"; a = a ^ b; // storing the xor of a and b in a b = a ^ b; // storing the value of the original a in b a = a ^ b; // storing the value of the original b in a cout << "After Swapping : a = " << a << " and b = " << b << "\n";}

Output :

Before Swapping : a = 1 and b = 2After Swapping : a = 2 and b = 1

Explanation :

In the above code, we first stored the xor of both the numbers in the first variable. Then, we store the original value of the first variable in the second variable by XORing the second variable with the sum. Similarly, we change the value for the second variable as well. Thus, we swapped the two numbers without using a third variable.



Discussion

No Comment Found