7. Control Flow

In code, selection and loops are two of the basic structures of computer programming, and are very critical in most programs. At runtime, when we execute our program, there is only one path through our code that will be executed due to a given set of selections. This is known as the thread of execution. In this way, we can alter or control the flow of statements in a program using basic frameworks like selection and loops, which are known as control flow structures. 

Selection

If-Else Statements

If and else statements are one way which allows for the selective execution of part of a program, contingent on some condition. The code inside an if statement will execute only if the specified condition is true. A variety of conditions may be used by implementing different logical and relational operators. In C++, the general syntax for an if statement is: 

Here, the condition that will determine whether the code in the if statement executes or not is placed in parentheses, and the actual expression(s) that are to be executed are to be placed in the curly braces. It is useful to note that the curly braces are optional if the “expression” is only one line of code. However, if you wish for more than one line of code to execute inside an if statement, you will need to include the curly braces. The code inside an if statement will only execute if the condition is deemed to be true. If the condition is false, the statements inside the if statement will not execute and the program will skip to the next line of code outside of the if statement. 

An example of the if statement in use may make this easier to understand. In the code below, we use an if statement to cout that the variable a is greater than 5 only when a actually is greater than five. The condition here is a>5 and the expression is the words that are displayed if this is true. The program will only cout the statement when the condition a>5 is true, otherwise only “Done” will be displayed, which is provided as a reference in the code that will execute without regard to the if statement. 

We can also see how curly braces are necessary when there is more than one line of code inside the if statement in the picture below. The top two boxes show how, with one line of code, curly braces are optional, while the if statements with multiple lines of code in the lower two boxes produce different results. Feel free to try this code on your own to prove to yourself how this works! 

In code, if statements are usually followed by else statements. These function similarly to their if statement counterparts, but don’t require you to specify the condition. Else statements will execute when the if statement(s) that come before it are all false. This can be thought of as kind of like a last case scenario - it will be the action that occurs if nothing else is true. The general syntax for an else statement is: 

When using if-else statements, you may want to have more than one condition checked before your code defaults to the else block of code. Instead of using multiple if statements in a row (don’t do this), you can use else if statements. These should be used in between the initial if statement and the ending else statement. The overall syntax for if, else if, and else statements is summarized below: 

If the initial if statement is false then the else if statement will be checked and executed if true. If that is found to be false, any following else if statements will be checked in sequence until one of them is true, or otherwise the else statement will execute. 

Given this example below, what do you think will be returned in each of the cases a = 1, 5, and 9? 

Try to think through this on your own first before continuing on to the answer.

Switch-Case Statements

Another way to incorporate selection into your programs is by using switch-case statements. These statements allow for a variable to be tested against a list of constant values (each case) for equality, and when a match is found, the code in that case will be executed. The basic syntax for switch statements is: 

The default and break statements are optional, but the breaks are needed to prevent the execution of statements in subsequent cases, which is most likely what you would want when utilizing switch-case selection. Including the break statements can also cut down on the time it takes for your program to execute, making your code more efficient. The default case acts similarly to the else in if-else statements, where it will run if none of the other cases match the condition variable.

Here is a quick quiz to test what you’ve just learned. In the example below, which case label is illegal? Analyze the code closely and make an educated guess as to which won’t work. Then look at the answer below and try and edit the code yourself to see why you were right or wrong. 

If you guessed that the Wednesday case is wrong, you are correct! Since the wed integer was not declared as a constant, it is not a valid case. This may be a bit confusing to understand at first. The Tuesday case is valid, however, because it is declared as a constant and the Monday case is also valid because the boolean value false is equivalent to 0. You might think that the Thursday case is the illegal one, but ‘t’ is a constant character (character literal). 

Loops

For and While

In programming, loops are commonly used when you need to repeatedly execute a block of code. The statements inside of the loop will continue to execute until a certain condition is reached or while a specified condition remains a specified value. At the beginning of each loop iteration the condition will be evaluated, and if it has not been reached the loop will execute again, continuing through more iterations until this is no longer the case. Loops can either be entry controlled loops where the condition is tested before entering the body of the loop or exit control loops, where the condition is evaluated at the end of the loop, meaning that the code will execute at minimum once. For the sake of this activity we will only consider entry controlled loops, but it is good to understand that there are other loop structures as well. In particular, we will discuss for and while loops, the two most common loops. 

A while loop is good to use in situations where you do not know the exact number of iterations that need to be executed beforehand. It is also relatively simple in terms of its syntax. It only requires you to specify its condition in parentheses, and all of the statements that go inside the loop can be placed inside curly brackets. The code in the brackets will continue to run as long as the initial condition stays true, so it is important to ensure that your loop will terminate at some point. Do not create an infinite loop! This is very bad. You can avoid this by initializing a counter outside of the loop and updating it at the end of each loop iteration in a way that you know won’t continue on forever. 

A quick note on scope:

It is important to understand the scope of your variables, that is the extent of your program within which a variable can be accessed. Variables can only be used after they are declared, otherwise an error will be returned. Additionally, any variables that are declared inside a loop or function (you will learn about these later) essentially live inside that area - they cannot be used outside of the scope in which they are declared. 

A for loop, on the other hand, has slightly more complicated syntax than a while loop. A for loop can be used when you know how many times you want the loop to execute, and requires you to create a loop variable to control the loop. Instead of simply putting the condition in parentheses and incrementing a counter that’s declared outside the loop, in a for loop a variable is initialized to a start value and incremented also within the parentheses as can be seen below. Each of the parts in parentheses should be separated by semicolons, just as you would use to end a line of code. The for loop will update the loop variable after each iteration and execute again until the condition is met. 

There are some operator shortcuts that will make your programming life a lot easier when coding with loops. These are shown in the table below, where the column on the right contains the shortcuts for their equivalent expressions on the left. The increment and decrement operators (the first two rows) are especially useful, and the ++ or -- can be written before or after the variable (e.g., x++ or ++x).

Now let’s do a quick exercise! There is an error in each of the examples below. Can you find them? Use what you’ve learned to try and figure it out on your own first, then continue on to the answers.

Answers:

In Case A, we run into a scope issue. The variable a is declared inside the while loop instead of in main, and thus produces a compiler error. Case B results in an infinite loop. The int i is initialized at 0 but after each iteration is decremented, and therefore will never reach the condition where i is not less than or equal to 5. The programmer’s intent here was probably to increment i, not decrease its value. We run into a similar issue in Case C, where updating the variable is forgotten entirely. We need to make sure that the variable upon which the condition is dependent changes at the end of each iteration of the loop.