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).
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.
Alternate Solution :
Time Complexity: O(1)
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 firstname.lastname@example.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.
- A C Programming Language Puzzle
- std::string::assign() in C++
- vector :: assign() in C++ STL
- Assign other value to a variable from two possible values
- forward_list assign() function in C++ STL
- deque assign() function in C++ STL
- list assign() function in C++ STL
- C++ 17 | New ways to Assign values to Variables
- Conditionally assign a value without using conditional and arithmetic operators
- Continue Statement in C/C++
- goto statement in C/C++
- Switch Statement in C/C++
- Break Statement in C/C++
- Nested switch statement in C++
- Print "Even" or "Odd" without using conditional statement