Chapter 5. Variables, decisions, and procedures

 

In this chapter, we’ll experiment with three powerful programming ideas. First we’ll look at how programs can remember and use pieces of information using variables. You’ll learn how programs can ask questions and make decisions using comparison operators and control blocks. Then we’ll look at how you can split up programs into reusable chunks called procedures, and why you will want to do this. Along the way, we’ll also look at some debugging and commenting tools that will help you troubleshoot pesky errors (programmers spend lots of their time doing this).

Remembering useful things

Often you’ll want an app to remember something that just happened so it can do something else later. Here are some examples:

  • Keeping score —How many coins have been collected? How many lives have been lost? In a fitness app, you might want to remember how many steps someone has taken during a run.
  • Tracking other game events —For example, a player may have picked up a magnifying glass; if they have it later, they can use it to examine a fingerprint.
  • Storing a list of contacts —A text message uses contacts in a communications app.
  • Using the start and end destination in a navigation app —This way, you know how far you’ve travelled and how far you have to go.

Total recall: naming and retrieving variables

 
 
 
 

Flattery app

 
 
 

Decisions, decisions: using variables to choose an action

 
 
 

Prankster Flattery app (Personality Judge app)

 
 
 

Keeping track with comments

 

Changing variables

 
 
 

Dice Roll app

 
 
 

Guess What I Am Thinking app

 
 
 
 

What did you learn?

 
 

Test your knowledge

 
 
 

Try it out

 
 
sitemap

Unable to load book!

The book could not be loaded.

(try again in a couple of minutes)

manning.com homepage
test yourself with a liveTest