The value of x is input from the user. "Nested if" statements are to be used to evaluate the above function. The output Y is to be displayed
I can solve the above question using if else statements which is pretty straightforward. However, I am not able to do it using nested if statement. Is it possible to write the code for the above function using nested if and without using else
you can do it a dozen ways, so I would time it to see which is fastest. Assuming its <0 for -1..
eg
char y = (char)(x>0); //x is 0 if equal or less than x, and 1 if > x now.
if( x < 0) y = -1; //correct for less than zero if needed.
now, that isn't nested because you only needed 1 if statement. It is doable to write it with extra unnecessary if statements as well.
1 2 3 4 5 6
y = 0;
if(x) //extremely inefficient nested approach.
{
if(x < 0) y = -1;
if(x > 0) y = 1;
}
using a boolean expression to get 1 or 0 does not incur a jump. Its very powerful to exploit that.
I have a lot of problems, but I can still count to 3 :P
1 2 3 4 5 6
y = 0; //1
if(x) //extremely inefficient nested approach.
{
if(x < 0) y = -1; //2
if(x > 0) y = 1; //3
}
I have to back @ne555 on this one. There may be 3 assignment statements, but assignments 2 and 3 will never both happen. Thus, there will be at most 2 assignments.
Ok, if you mean executing, sure, its 2. I see what you were saying. I just meant in the code.
I wonder if we have helped, or more confused, the OP?
We didn't even go down the bitwise approaches... you can jack any sort of ints or doubles into something and strip off the sign bit.
but, lastchance's answer is probably the best way to actually code it for this specific problem, unless you want to go bitwise (which has NO comparisons at all but is not resusable across types).
The problem, like many in school -- it may make you think, but its not really showing you anything useful. Some languages, eg assembly and very low level languages, may not have an else, so its useful as a brain exercise. (Typically you do as I did, and set the else first, and modify it if the other things were true, for those languages). C++ has an else, and c++ has at least 2 ways to avoid using any if /else type logic at all (lastchance's answer and bitwise), both of which are preferable.
Note that some of what we are doing keys off zeros and ones though. zeros, ones, and powers of 2 let you do near-magic things in a computer!
If it were this problem:
Y = 1 if x > 1000
Y = -1 if x< -1000
else Y = 0
what is the most efficient way to do it? Its not as cheesable ... can you see anything good to do here? (there is still some cute things you can do, but they are more challenging).