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.
/* 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 = %d\n", a, b); // Print all if(a > b) // If a > b condition is true { print("a is larger \n"); // ...then print this message } }
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.
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){...}.
Comparisons with negative numbers can be interesting.