Open In App
Related Articles

Set a variable without using Arithmetic, Relational or Conditional Operator

Improve Article
Improve
Save Article
Save
Like Article
Like

Given three integers a, b and c where c can be either 0 or 1. Without using any arithmetic, relational and conditional operators set the value of a variable x based on below rules –

If c = 0
    x = a
Else // Note c is binary
    x = b.

Examples:

Input: a = 5, b = 10, c = 0;
Output: x = 5

Input: a = 5, b = 10, c = 1;
Output: x = 10

Solution 1: Using arithmetic operators
If we are allowed to use arithmetic operators, we can easily calculate x by using any one of below expressions –

x = ((1 - c) * a) + (c * b)

OR

x = (a + b) - (!c * b) - (c * a);

OR

x = (a * !c) | (b * c);




#include <iostream>
using namespace std;
  
int calculate(int a, int b, int c)
{
    return ((1 - c) * a) + (c * b); 
}
  
int main()
{
   int a = 5, b = 10, c = 0;
      
   int x = calculate(a, b, c);
   cout << x << endl;
      
   return 0;
}


Output:

5

 
Solution 2: Without using arithmetic operators
The idea is to construct an array of size 2 such that index 0 of the array stores value of variable ‘a’ and index 1 value of variable b. Now we return value at index 0 or at index 1 of the array based on value of variable c.




#include <iostream>
using namespace std;
  
int calculate(int a, int b, int c)
{
   int arr[] = {a, b};
   return *(arr + c);
}
  
int main()
{
   int a = 5, b = 10, c = 1;
      
   int x = calculate(a, b, c);
   cout << x << endl;
      
   return 0;
}


Output:

10

If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.


Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now!

Last Updated : 29 May, 2017
Like Article
Save Article
Previous
Next
Similar Reads