...

/

Controlling the Execution Path

Controlling the Execution Path

Learn how statements are selectively executed based on the conditions.

Controlling the execution path

We learned that the code within a program is executed in sequence. A sequence is one of the three basic logical structures we have in programming. In this chapter, we’ll cover the other two, selection and iteration.

Selection statements

There are situations when we only want to execute some code if a condition is met. For example, recall our application from an earlier chapter that turned on the outdoor lights—we had a condition that said if our phone detected that we were within a given range from our house, it should send a signal to the home computer. The figure below shows the action of entering the range.

Press + to interact
The phone detects that it is within a given range from our house
The phone detects that it is within a given range from our house

Then, we have a condition. We used the illustration shown in the figure below to indicate that when the condition was true, that is, when we’re within the range, a signal should be sent to the home computer:

Press + to interact
The condition is met, so the code for sending the message can be executed
The condition is met, so the code for sending the message can be executed

Let’s break it down a bit more and consider the actual steps involved. The application on the phone would need to perform the following steps:

  1. Ask the GPS on the phone for the current
...