By Mrunmay Phanse


2018-10-11 14:13:41 8 Comments

Can someone guide me how to put this properly in an if-else statement. Consider the following if statement, where doesSignificantWork, makesBreakthrough, and nobelPrizeCandidate are all boolean variables:

if (doesSignificantWork) {
    if (makesBreakthrough)
        nobelPrizeCandidate = true;
    else
        nobelPrizeCandidate = false;
}
else if (!doesSignificantWork)
    nobelPrizeCandidate = false;

First, write a simpler if statement that is equivalent to this one. Then write a single assignment statement that does the same thing.

3 comments

@Bob Jarvis 2018-10-11 14:22:37

A simpler if statement is:

if (doesSignificantWork && makesBreakthrough)
  nobelPrizeCandidate = true;
else
  nobelPrizeCandidate = false;

@Blaze's answer gives you the simplest one-liner. An alternative is

nobelPrizeCandidate = (doesSignificantWork && makesBreakthrough) ? true : false;

@anatolyg 2018-10-11 14:22:11

You can make a truth table. The first step is to identify inputs, and write down all combinations of their values.

Input   Output
d   m   n
0   0   ?
0   1   ?
1   0   ?
1   1   ?

Then fill the correct output values

Input   Output
d   m   n
0   0   0
0   1   0
1   0   0
1   1   1

You should now see that the output function corresponds to logical AND (&&).

@Blaze 2018-10-11 14:16:29

if (doesSignificantWork) {
    if (makesBreakthrough)
        nobelPrizeCandidate = true;
    else
        nobelPrizeCandidate = false;
}
else if (!doesSignificantWork)
    nobelPrizeCandidate = false

Is equivalent to

nobelPrizeCandidate = (doesSignificantWork && makesBreakthrough);

Related Questions

Sponsored Content

9 Answered Questions

[SOLVED] Improve INSERT-per-second performance of SQLite?

26 Answered Questions

[SOLVED] Too many 'if' statements?

4 Answered Questions

[SOLVED] Why does C not have a logical assignment operator?

5 Answered Questions

[SOLVED] How to write if/else with boolean in Bash?

4 Answered Questions

[SOLVED] My if statement returns unexpected results

  • 2016-08-24 18:11:39
  • Allan Mayers
  • 86 View
  • 0 Score
  • 4 Answer
  • Tags:   c if-statement

2 Answered Questions

[SOLVED] C program treats an if statement as false when it is in fact true

  • 2015-06-09 05:33:36
  • wiseaddict
  • 34 View
  • 0 Score
  • 2 Answer
  • Tags:   if-statement

2 Answered Questions

[SOLVED] Good programming practice to include ELSE statements for most IF statements?

  • 2014-01-27 18:32:59
  • sherrellbc
  • 865 View
  • 3 Score
  • 2 Answer
  • Tags:   c if-statement

3 Answered Questions

[SOLVED] Java if statement equality

  • 2013-11-15 00:47:47
  • Toms Bugna
  • 120 View
  • -2 Score
  • 3 Answer
  • Tags:   java if-statement

1 Answered Questions

6 Answered Questions

[SOLVED] How do you put a if, else statement within a for statement

Sponsored Content