Make a Decision
A common program decision is what to do with an output, such as a light, speaker or motor, based on one or more inputs, such as measurements from sensors.
Next, we will look at some example programs that make decisions based on the values stored by certain variables. After you are through with this primer and into programs for simple circuits, you will see many examples of decisions based on sensor inputs.
This example program initializes and then displays the values of variables named a and b. After that, it checks if a is larger than b, and if so, it prints a message saying so.
- Click the Open Project button.
- If you aren’t already there, navigate to …SimpleIDELearnExamplesC IntroBasics.
- Open Make a Decision.side.
- Examine the program. Do you expect it to display one message, or two?
- Set the power switch to position 1 if it isn’t already (if applicable for your board).
- Click the Run with Terminal, and compare the result from the Propeller (displayed in the SimpleIDE terminal) against your prediction.
- What do you think will happen if you swap the values of a and b. Try it, and then re-run the program.
/* Make a Decision.c If a condition is true, display a second message. */ #include "simpletools.h" // Include simpletools int main() // main function { int a = 25; // Initialize a variable to 25 int b = 17; // Initialize b variable to 17 print("a = %d, b = %dn", a, b); // Print all if(a > b) // If a > b condition is true { print("a is larger n"); // ...then print this message } }
How the Code Example Works
The program initializes a to 25 and b to 17 and displays both those values in the SimpleIDE Terminal. Then, it uses if(a > b) to decide whether to execute the contents of a code block, which contains the print(“a is larger n”) statement. If a is greater than b, it will print the second message. If it’s equal to or less than b, it will not print the message.
Did You Know?
The > symbol is called a relational operator. Here is a list of relational operators and their meanings:
== Equal to != Not equal to > Greater than >= Greater than or equal to < Less than <= Less than or equal to
In C language, the expression a > b returns 0 if its false (a is not really greater than b) or 1 if it’s true (a is greater than b). So, in if(a > b){…}, the block of code inside the braces gets executed when a > b evaluates to 1, as in if(1) {…}. The code block does not get executed if a > b returns 0, as in if(0){…}.
Try This
Comparisons with negative numbers can be interesting.
- Try changing a to –25 and b to –17.
- Think about which number is larger.
- Re-run the program and check the result.
Your Turn
- Expand your program with more if code blocks that test each of the relational operators introduced in the Did You Know section.