The if Conditional
When programming a computer, we often want a machine to make decisions automatically. For example, we might want the computer to add some numbers, then determine if the sum is greater than 10. Or, we might want a program to search the Internet and determine if a picture is a cat, or any number other reasons (e.g., self-driving cars should stop if there is a pedestrian in their way). Quorum uses the if construct for decision making, like many other programming languages. For example, suppose we wanted to test whether an integer is greater than 10. We would do this like so:
integer a = 11 if a > 10 output a end output "The end"
Try the above code block.
In this case, if a happens to be greater than 10, then Quorum will execute any computer code that is between the top line of the if and the "end" at the bottom. Sometimes, however, we want to test multiple conditions to see if any of them are true. We can do this by using a construct called elseif, which only executes when the the statements previous to it were false and the current one is true. We use else just like we use if, except with a different word in the beginning. Here is an example:
integer a = 1 integer b = 1000 integer c = 0 if a > 100 c = 1 elseif b = 100 c = 2 end output c
Try chaining if statements and elseif statements.
Similarly, we may want to take an operation if none of the if statements or elseif statements were true. In this case, we have a catch all we can use, called else. Like before, else executes a block of code in it, but in this case only when all previous if statement tests failed. Building on previous examples, we can use else like so:
integer a = 1 integer b = 1000 integer c = 0 if a > 100 c = 1 elseif b = 100 c = 2 else c = 3 end output c
In this case, the above code will first test to see if a is greater than 100. If that is so, it will execute the statement c = 1. However, if the value of a is not greater than 100, the code will then test to see if b is greater than 100. If that is the case, c will be set to 2. If neither a, nor b, are greater than 100, c will be set to 3. With this code as a guide, practice using if statements in the development environment below.
Try the above code blocks.
In the next tutorial, we will discuss actions, which describes how to use actions to provide additional behaviors our code can do.