Chapter II.4. Making Decisions by Branching

The simplest program lists commands one after another in a sequence, much like following the steps of a recipe. Follow a recipe step by step and you always create the same dish. If a program lists commands step by step, the computer always produces the same result.

In some cases, you may want a program to do the exact same thing over and over again, such as a simple program to display traffic signals. However for most programs, you want the computer to react to outside data. To make a computer respond in different ways, a program needs to offer two or more choices for the computer to follow.

When you quit a program, the program may ask, "Do you really want to exit?" At this point, the program is giving the computer a choice of two possible actions to take based on your answer.

If you answer Yes, the computer quits the program. If you answer No, the computer keeps running the program.

When a program gives the computer a choice of two or more commands to follow, that's called a branching or decision statement.

All branching statements work the same way:

  • A comparison operator (or a conditional expression) compares an expression (such as A > 45) to determine a True or False value.

  • The branching statement offers at least two groups of commands for the computer to follow based on whether its comparison is True or False.

Picking One Choice with the IF-THEN Statement

The simplest branching statement is an IF-THEN statement, which looks like this:

IF (Something ...

Get Beginning Programming ALL-IN-ONE DESK REFERENCE FOR DUMMIES® now with the O’Reilly learning platform.

O’Reilly members experience live online training, plus books, videos, and digital content from nearly 200 publishers.