Better Decision-making with If...Else Statements
Last updated
Last updated
In the previous section, we learned how to use the If statement in Sonar (read it , if you skipped that, or if you need a refresher).
In this section, we will build on our knowledge of If statements to make our programs make more complex decisions using the If...Else statement.
Sometimes, we make sentences that resemble:
"if it rains today, I will not go out; but if it doesn't, I will"
"if today is a weekday, I will have to go to school; but if it isn't, I will go out to play"
"if I click the Netflix icon, my iPhone will start the Netflix app; but if I click the TikTok icon, my iPhone will start the TikTok app"
Each of these sentences have two conditions that are related. The two conditions are "opposites" (i.e they cannot be true at the same time).
it cannot rain and not rain at the same time
it cannot be a weekday and the weekend at the same time
you cannot click the Netflix app and the TikTok app at the same time (well, you can try –– but you can't; trust me, I tried)
Each of these sentences look like this:
For example:
Many countries have a legal drinking age of 18 years. We can write a program that checks whether a person is able to drink alcohol or not.
If we change age
to a number greater than or equal to 18, the person will be allowed to drink:
We can make our traffic controller better by replacing our If statements with If-else:
Take a minute to think about our improved program to be certain you understand it.