Hi I have been asked this question at school. I can't seem to figure it out.
Write a c program without using any conditional statement (if/else/switch:case/while/for etc.) which outputs :
1535(integer) if input is -1(integer)
else it outputs the input(if not -1)?
Question is suppose to assess my logical skills rather than c programming skills.
Considering:
(question is suppose to assess my logical skills rather than c programming skills)
I assume that language-lawyering like "ternary operators are not a conditional statement" to be against the spirit of the question. So let's tackle this from a completely branchless point of view.
This intuitively feels to me like a job for multiplication, since the "0 swallows everything" and "1 leads to a no-op" properties of the operation would allow us to manage different "paths" at the same time.
In other words, if we had a magic function f() for which f(0) == 1 and f(anything else) == 0, then we could leverage the fact that x * 0 == 0 and x * 1 == x to "combine" both possible answers:
int answer(int v) {
int f_result = f(v + 1); // Offset the -1 to 0, which becomes 1, anything else becomes 0
int f_inv = f(f_result); // 1 becomes 0, 0 becomes 1
return
v * f_inv +
1535 * f_result;
}
So, all we need now is a f() that returns a 1 for 0, and 0 for anything else.
It's simply the
!unary operator:int f(int v) { return !v; }
I can suggest the following approach
#include <stdio.h>
int main(void)
{
const int DEFAULT_VALUE = 1535;
printf( "Enter any number or -1: " );
int n = -1;
scanf( "%d", &n );
printf( "%d\n", ( n == -1 ) * DEFAULT_VALUE + ( n != -1 ) * n );
return 0;
}
The program output might look like
Enter any number or -1: -1
1535
or for example
Enter any number or -1: 10
10
The key statement of the program is the following
printf( "%d\n", ( n == -1 ) * DEFAULT_VALUE + ( n != -1 ) * n );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With