Decisions #
Until now our programs have simply been linear, they start at the top and every line of code we have written gets executed one after the other. Now we are going to introduce a group of operators and a statement that allows us to decide if certain lines of code are run or skipped over.
How computers make comparisons #
In order to make a decision, we need to compare values, e.g. Is the input value greater than 0? Is Mario touching the ground?
We can perform these comparisons using the relational operators that you are already familiar with:
<Less than<=Less than or equal to>Greater than>=Greater than or equal to==Is equal to!=Is not equal to
All of the above are binary operators, that means that they need two operands to work on, e.g. 5 < 10. These relational operators then evaluate to either 1 or 0.
C treats 0 as false, and any other value as true.
We also have logical operators that we can use to combine the results of multiple comparisons:
&&Logical AND - returns1if both operands are1,0if either is0||Logical OR - returns1if either operand is1, and0if both are0!Logical NOT - only takes one operand and inverts1to0and vice-versa
We can then combine all of these with the if statement, which allows us to conditionally execute blocks of code.
if statements
#
An if statement comprises the keyword if followed by brackets in which a condition is tested, and then a block that is executed if that condition is evaluated as true (1):
if(5 < 10)
{
printf("5 is less than 10!");
}
The if statement executes the block of code immediately following it if the expression in the () evaluates to 1. If it evaluates to 0, it won’t execute the block immediately following it.
else
#
Sometimes you might also want code to execute if the condition is false, so you can append else to the end of it:
if(age >= 18)
{
printf("You can vote!");
} else
{
printf("You can't vote.")
}