Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to write else if as logical statement?

I want to write an if-else statement as a logical statement. I know that:

if (statement1){
   b=c
}
else{
   b=d
}

can be written as:

b=(statement1 && c)||(!statement1 && d)

But how do I write the following if-else statements as logical?:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

if (statement1){
   b=c
}
else if (statement2){
   b=d
}
else{
   b=e
}

I have thought of something like:

b=(statement1 && c)||(statement2 && d)||((!statement1&&!statement2) && e)

I’m sorry if there is already a post about this. I have tried, but couldn’t find anything similar to my problem.

>Solution :

As with all logical statement building, it’ll be easiest to create a truth table here. You’ll end up with:

+--+--+--------+
|s2|s1| result |
+--+--+--------+
| 0| 0|   e    |
+--+--+--------+
| 0| 1|   c    |
+--+--+--------+
| 1| 0|   d    |
+--+--+--------+
| 1| 1|   c    |
+--+--+--------+

So un-simplified, that’ll be

(!s1 & !s2 & e) || (!s2 & s1 & c) || (s2 & !s1 & d) || (s1 & s2 & c)

This can be simplified by combining the two c results and removing the s2:

(!s1 & !s2 & e) || (s2 & !s1 & d) || (s1 & c)

(note that this will be faster in C++ and match the if statements closer with s1 & c as the first term. This will especially make a difference if evaluating any of these values will cause outside effects)


Note that what you built,

(statement1 && c)||(statement2 && d)||((!statement1&&!statement2) && e)

will function incorrectly if statement1 is true, c is false, and both statement2 and d are true (you’ll get a result of true when you should have false).

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading