Programming puzzle (Assign value without any control statement)

Given four integers ‘a’, ‘b’, ‘y’ and ‘x’, where ‘x’ can only be either zero or one. Your task is as follows:

  • If ‘x’ is zero assign value ‘a’ to the variable ‘y’
  • If ‘x’ is one assign value ‘b’ to the variable ‘y’.

It is not allowed to use any conditional operator (including ternary operator).

Examples:

Input  : a = 3, b = 7,  x = 1
Output : y = 7

Input : a = 3, b = 7, x = 0
Output : y = 3

The idea is to create an array of size two where first element is ‘a’ and second element is ‘b’. We use x as index in the array.

// CPP program to pick a value among two
// according to value of a third variable.
#include <iostream>
using namespace std;

// Returns a if x is 0 and returns
// b if x is 1.
int assignValue(int a, int b, bool x)
{
    int arr[] = {a, b};
    return(arr[x]);
}

// Driver code
int main()
{
    int y = assValue(3, 7, 0);
    cout << y
    return 0;
}

Output:

 7

Alternate Solution :

// CPP program to pick a value among two
// according to value of a third variable.
#include <iostream>
using namespace std;

// Returns a if x is 0 and returns
// b if x is 1.
int assignValue(int a, int b, bool x)
{   
    return (1 - x)*a + x*b;
}

// Driver code
int main()
{
    int y = assValue(3, 7, 0);
    cout << y
    return 0;
}

Output:

 7

Thanks to Forrest Smith for suggesting above solution.

This article is contributed by Maajid Bashir. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@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.

GATE CS Corner    Company Wise Coding Practice

Recommended Posts:



0 Average Difficulty : 0/5.0
No votes yet.