Lesson 5

Control the flow


We've covered variables, data types, arithmetic operators and some basic calculations. Now we are going to look at how we can control the flow of our code depending on the values of our variables.


The first form of flow control that we're going to take a look at is called an if-statement. An if-statement will return either true or false and execute a certain piece of code depending on the value.

Let's take a look at how it works:

What we have here is very simple. We have a variable named age with the value 15 and then use our if-statement to decide whether the first printf statement should be executed, or if the second one should. Not that all if-statement have an opening and a closing parenthesis (( and )) with a condition inside (age >= 18).

If we translated our if-statement into pure English, it can be read as:

"If the age is greater or equal to 18, then execute the following block of code""otherwise, if the condition is not met, execute this block of code".

The else condition will be executed if the condition is not met. Try to change the value of age to 18 or more and you will see that the result of the execution is different, because the other condition will be true.

If-statements are one of the most common code pieces you'll use. Some examples of what you can do with if-statements are:

  1. Check if a user's input is valid

  2. Check if a player won or lost a game

  3. Check if a user guessed a randomly chosen number correctly

In an if-statement you can also use something called else if, which will be checked if the first if-condition isn't met. Let's take a look at how it works:

As you can see, we can print out different things to the screen depending on how our variable changes. If age has a value of 1 we want to run the first printf statement, but if age is 2, we want to run the other one instead etc...

If none of these requirements are met, we decide to output the else statement which is "You are four years or older!". Note that this one does not have any parenthesis with a specific condition . That's because this block will be executed only if no other requirements are met, and therefore doesn't require a condition.

In the next lesson we will take a look at other types of logical operators.



Be the first to comment!