Make Complicated Decisions

Your programs will often need to decide what to do based on if one condition AND another condition are true.  Another thing your code might need to check for is if one condition OR another condition is true.  Decide on Multiple Conditions.c decides if one condition AND another condition are true using the && operator.

  • Use the Open Project button to open the Decide on Multiple Conditions.side.
  • Examine the program, do you expect it to print one or two messages?
  • Set the power switch to position 1 if it isn't already (if applicable for your board).
  • Click Run Project with Terminal, and compare the result from the Propeller to your prediction.
/*
  Decide on Multiple Conditions.c
 
  Make a decision based on two conditions.  
*/

#include "simpletools.h"                      // Include simpletools

int main()                                    // main function
{
  int a = 100;                                // Initialize a variable to 25
  int b = 17;                                 // Initialize b variable to 17
  print("a = %d, b = %d\n", a, b);            // Print all
  if((a > b) && (a == 100))                   // If a > b AND A == 100
  {
    print("a is larger than b,\n");           // Then print this message
    print("AND a is 100!\n");                 // Then print this message
  }
}

 

How it Works

The statement if((a > b) && (a == 100){...} translates to “if a is greater than b AND a is equal to 100 then, do what’s in the braces.” 

 


Did You Know?

The && operator is called a logical operator.  Your logical operator options are:

&&     Checks for if one condition AND another condition
||     Checks if one condition OR another condition is true
!      Inverts the result from true to false (1 to 0) or vice-versa

 

Try This

By now, you can probably tell that both conditions have to be true for the AND logical operator to evaluate to true (so that it will execute its code block).  For one condition OR another to evaluate to true, either one or both conditions can be true.  

  • Use the Save Project As button to save a copy of your project as Test OR Conditions.
  • Do you expect it to display the second message or not?  Test your result
  • Modify a and b to make it only print one message.

 

Your Turn

  • Write a program that prints a special message, but only if the value of the a variable is in the 100 to 200 range.