Chapter 5. Computers make decisions, too!

 

This chapter is all about how to write code that makes decisions.

This chapter covers

  • What conditions are
  • How to use conditions to make decisions in programming
  • How to use a basic if statement in condition checking
  • How to use the else and else if clauses with the if statement
  • What the basic conditional operators are
  • What the switch statement is and how to use it

You’re all set to cover your fifth milestone: Computers make decisions, too! You make decisions all the time. You decide to do something depending on some bit of information in life. If it’s raining, for example, you use an umbrella. You make the decision to carry an umbrella based on whether or not it’s raining.

Your code needs to make decisions, too. Imagine an app that can tell you whether you need an umbrella. This app checks to see whether it’s raining. If so, the app outputs the information that you need an umbrella.

Conditions with the if statement

Think of a condition as a question that can have only a true or false answer. If the answer, or result, of the condition is true, you do something. You use conditions all the time without even noticing. Table 5.1 shows some examples of simple conditions.

Table 5.1. Examples of simple conditions (view table figure)

Condition

Result

If the weather is cold = TRUE Wear a coat.
If I am thirsty = TRUE Drink something.
If I am sick = TRUE Don’t go to school.

App: Which Number Is Bigger?

switch statements

App: The Mystery of the Entered Number

Check your app knowledge

App-Exercise: Gold, Silver, Bronze

App-Exercise: tTables the Times Tables Bee!