Assign other value to a variable from two possible values in C++


Problem Statement

we have to assign a variable the value of other variables from two possible values without using any conditional operator.

Description

In this problem, we are given a variable let's say a which can have a value of any of the two variables x and y. Now, we have to create a program to assign the value of another than its current value without using any conditional operator i.e. we can’t check the value of x.

Let’s take an example to understand the problem better −

Input : a = 43 ; x = 43 and y = 21
Output : 21

Explanation − the initial value of a is 43 so we need to return the other value i.e. 21 as the final value of a.

Since we are not allowed to check the value of an i.e. use of any sort of conditional statement is not valid in the code. So, we need to see alternate solutions to the swap value of the variable. For this, there can be multiple solutions but we are discussing most feasible and easy once here −

Using arithmetic operator

One of the easy ways to swap value is to use addition/multiplication of the two values and subtract/divide for respective opposite operations i.e subtract if we have done addition and divide if used multiplication.

So, the formula becomes −

a = x + y - a or a = x * y / a

But here the multiply and divide operations are more costly and may sometimes throw errors. So, we have used addition - subtraction combo for this.

Example

 Live Demo

#include <iostream>
using namespace std;
int main(){
   int x = 45;
   int y = 5;
   int a = x;
   cout<<"Initial value of a is : "<<a;
   a = x+y - a;
   cout<<"\nAfter changing the value of a is : "<<a;
}

Output

Initial value of a is : 45
After changing the value of a is : 5

Using bitwise XOR operator

A more effective way could be using the bitwise XOR operator.

So, the value would be changed in the following manner −

a = x^y^a;

Example

 Live Demo

#include <iostream>
using namespace std;
int main(){
   int x = 56;
   int y = 78;
   int a = x;
   cout<<"Initial value of a is : "<< a;
   a = x^y^a;
   cout<<"\nAfter changing the value of a is "<<a;
   return 0;
}

Output

Initial value of a is : 56
After changing the value of a is 78

Updated on: 24-Oct-2019

415 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements