Summary of the Program Control Structures

Learn what we have covered in this chapter.

We'll cover the following

Chapter summary

Sequence, selection, and iteration are the three pillars that programming rests upon. In this chapter, we’ve covered the latter two.

Selection is when we test values in variables using a condition that can be either true or false. If our test turns out to be true, we can let the program execute a block of code. If it turns out to be false, we can have another block that only runs in this case. This is done with the help of if statements.

Sometimes, we have multiple options to choose from, and we need to pick one. We could then use a switch statement. Using it instead of an if statement can make code less verbose and easier to read.

The common task of repetition can be done in at least four ways, with the most common being the for loop. This loop lets us iterate a fixed number of times.

When we don’t know how many times we want to iterate, we can use either a while loop or a do while loop. They will both iterate as long as a condition is true. This lets us write very flexible applications that might repeat something twice.

The difference between the while loop and the do while loop is where the condition is located. In a while loop, it comes at the beginning, and, in a do while loop, it comes at the end.

If we have a sequence of something, using a foreach loop is the best choice, because it will go through the sequence and give us one of its objects at a time. It’s a safe structure to use because it makes sure that we actually get all the values and don’t miss out on the first or the last one.

Get hands-on with 1200+ tech skills courses.