Chapter:Control flow in C

From Juneday education
Jump to: navigation, search

Control flow

Meta information about this chapter

Expand using link to the right to see the full content.

Introduction

Purpose

Goal

Concepts

Instructions to the teacher

Common problems

Chapter videos

All videos in this chapter:

See below for individual links to the videos.

Block

Description

When we want to group together code, most often because it belongs together in some way, we use block (or code block). You Start a block with {' and end it with }. All code in between is said to be the code block. The block could actually be empty but most often it contains one or more statements/instructions.

Note that variables declared inside a block of code are only visible (can only be used) inside the same block (or inside blocks declared inside the same block).

Videos

  1. Block (eng) (sv) (download presentation) (The presentation and video are based on Java but will do fine here)

Control flow introduction and if statement

Description

Let's start by a human example. If my shoelaces are not tied properly, I will tie them. This means I will only tie my shoelaces if they're not tied. With this simple example we want to show that we use if statements in our daily life all the time.

The IF-statement is a control flow construct that we can use if we want to execute a block of code only if a boolean expression is true. In its simplest form we write code with an if statement like this:

if (temperature>40) {
  printf("Please, turn on the fan");
}

In this example we print "Please, turn on the fan" if the temperature (the value of the variable temperature) is higher than 40. If the temperature is less than (or equal) to 40 we do nothing.

A slightly more complex if statement:

if (temperature>40) {
  printf("Please, turn on the fan");
} else {
  printf("You do not need to turn on the fan");
}

We added code that is executed if the temperature is NOT higher than 40. We did this by adding else in the if statement.

Our final example will be:

if (temperature>40) {
  printf("Please, turn the fan to MAX.");
} else if (temperature>30){
  printf("Please, turn on the fan modestly");
} else {
  printf("You do not need to turn on the air condition");
}

In this last example, we first check if the temperate is higher than 40. If it is, we output "Please, turn the fan to MAX." None of the other clauses of the if statement would execute. But if the temperature is NOT higher than 40 we continue and check if the temperature is higher then 30. If it is we output "Please, turn on the fan modestly" (and nothing else). If the temperature is not higher than 30 (or 40 for that matter) we output "You do not need to turn on the air condition".

Videos

  1. If (eng) (sv) (download presentation) (The presentation and video are based on Java but will do fine here)

Exercises

Note: this is so called pseudo code. It can't be compiled. The idea is that you shall focus on studying the if statement. No compilation is needed or possible.

  1. We have the following code:
    if (nr_of_students>90) {
    
        book_big_room;
    
    } else {
    
        book_medium_room;
    
    }
    
    a) let’s pretend that the number of students, reflected in the variable nr_of_students, are 123. What [statement] is reached?
    b) let’s pretend that the number of students, reflected in the variable nr_of_students, are 90. What statement is reached?
    c) let’s pretend that the number of students, reflected in the variable nr_of_students, are 89. What statement is reached?
  2. We have the following code.
    if (nr_of_students>90) {
    
        book_big_room;
    
    } else if (nr_of_students>20) {
    
        book_medium_room;
    
    } else {
    
        book_small_room;
    
    }
    
    a) let’s pretend that the number of students, reflected in the variable nr_of_students, are 123. What statement is reached?
    b) let’s pretend that the number of students are 90. What statement is reached?
    c) let’s pretend that the number of students are 89. What statement is reached?
    d) let’s pretend that the number of students are 21. What statement is reached?
    e) let’s pretend that the number of students are 20. What statement is reached?
    f) let’s pretend that the number of students are 5. What statement is reached?
    g) let’s pretend that the number of students are 0. What statement is reached?
  3. We have the following code.
    if (nr_of_students>90) {
    
        book_big_room;
    
    } else if (nr_of_students>20) {
    
        book_medium_room;
    
    } else if (nr_of_students>0) {
    
        book_small_room;
    
    }
    
    a) let’s pretend that the number of students are 5. What statement is reached?
    b) let’s pretend that the number of students are 0. What statement is reached?
  4. Look at the source code below:
            int age = 18;
    
            if (age>100) {
    
                printf("Wow, you're over hundred years old!");
    
            } else {
    
                printf("You're still young");
    
            }
    
    a) What do you think will be printed out?
    c) Change the value of age to 100. What will happen?
    d) Change the value of age to 101. What will happen?
  5. Look at the source code below:
            int age = 18;
    
            if (age>100) {
    
                printf("Wow, you're over hundred years old!");
    
            } else if (age>80) {
    
                printf("Wow, you're kind of old!");
    
            } else {
    
                printf("You're still young");
    
            }
    
    a) What do you think will be printed out?
    b) Compile the file and execute it to see what is actually printed.
    c) Change the value of age to 80. What will happen?
    d) Change the value of age to 90. What will happen?
    e) Change the value of age to 100. What will happen?
    f) Change the value of age to 101. What will happen?


Solutions

Expand using link to the right to see the full content.

  1. a) book_big_room
    b) book_medium_room
    c) book_medium_room
  2. a) book_big_room, since 123 i greater than 90
    b) book_medium_room, since 90 is not greater than 90 but greater than 20
    c) book_medium_room, since 89 is not greater than 90 but greater than 20
    d) book_medium_room, since 21 is not greater than 90 but greater than 20
    e) book_small_room, since 20 is not greater than 90 nor greater than 20
    f) book_small_room, since 5 is not greater than 90 nor greater than 20
    g) book_small_room, since 0 is not greater than 90 nor greater than 20
  3. a) book_small_room
    b) no statement inside the IF-statement is reached - execution will continue after the whole IF-statement
  4. Verify yourself by using the file: Main.java
  5. Verify yourself by using the file: Main.java
    The last two Main.java files are two distinct files!


Links

while

Description

A while loop is a construct in a programming language that allows code to be repeated as long as a boolean expression is true.

An example:

1 int counter = 3;
2 while (counter > 0 ) {
3   printf("Hi there!");
4   counter--; // decrease the value of counter so that we eventually will exit the loop
5 }

Let's go through the example:

  1. we declare and initialise (the first assignment) an integer variable, counter
  2. we start a while loop. This line means that we will keep looping/repeating as long as counter > 0. With the { we mark the beginning of the block to be executed for every loop.
  3. We simply output the text "Hi there!"
  4. The last thing we do in the block is the decrementing of counter so that the test will yeald false eventually
  5. End of the block of code to be executed in every loop

In the example above "Hi there!" will be printed 3 times. That is because we start with a value of 3 for counter and decrement it by one each iteration. The value will be, in order:

  1. 3 --- 3 > 0 is true
  2. 2 --- 2 > 0 is true
  3. 1 --- 1 > 0 is true
  4. 0 --- 0 > 0 is false - we won't enter the block here

Note that counter will finish at 0 and have the value 0 after the loop.

Videos

  1. while (eng) (sv) (download presentation) (The presentation and video are based on Java but will do fine here)

Exercises

Note: this is so called pseudo code. It can't be compiled. The idea is that you shall focus on studying the if statement. No compilation is needed or possible.

  1. Look at the code below.
        while (true) {
    
          set_color(RED);
    
        }
    
    How long does it execute?
  2. Look at the code below.
        while (false) {
    
          set_color(RED);
    
        }
    
    How many loops will be executed?
  3. Look at the code below.
        int counter=0;
    
        while (counter<3) {
    
          set_color(RED);
    
          counter++;
    
        }
    
    How many loops will be executed?
  4. Look at the code below.
        int counter=0;
    
        while (counter<3) {
    
          set_color(RED);
    
        }
    
    How many loops will be executed?
  5. Let's assume that the function get_temperature is connected to a thermometer and that the function returns an integer value which gives us the temperature in Celsius.
        while (get_temperature() < 20) {
    
              heat_up();
    
        }
    
    Btw, heat_up is a so called function connected to a radiator which will heat up the room.
    Try to explain how the code works.
  6. Look at the following code in
      printf("Hi there..");{
    
      printf("Hi there..");{
    
      printf("Hi there..");{
    
      printf("Hi there..");{
    
    Replace the four print statements with a while loop and one print statement.


Solutions

Expand using link to the right to see the full content.


  1. For ever. The while loop continues until the expression is false. Since the expression is always true the loop will continue for ever.
  2. None. The while loop starts if and continues until the expression is false. Since the expression is always false the loop will never be entered.
  3. Let's calculate this ourselves. We start with counter having the value 0, which is less than 3 so we're entering the loop. In that loop we increase, using ++, counter with 1.
    counter is now 1, which is still less than 3, so let's loop one more time and increase counter.
    counter is now 2, which is still less than 3, so let's loop one more time and increase counter.
    counter is now 3, which is NOT less than 3 so let's NOT loop anymore.
  4. For ever. The expression checks if counter is less than 3. Since counter is 0 it is also less than 3. In the loop no changes are made to the counter variable so the loop continues for ever.
  5. Until the temperature is 20 degress or higher we're calling heatUp function. When the room is 20 we continue with some other thing.... (the code below).
  6.   int i=0;
    
      while (i<4) {
    
        printf("Hi there..");
    
        i++;
    
      }
    
    You can also download source code here: While.java.


Links

for

Description

As with the while loop the for statement is used to loop (repeat) a block of code. The following code:

1 for (int i=0; i<3; i++) {
2   printf("Hi there!");
3 }

outputs "Hi there!" three times. How? Let's go through the code:

  1. we start be declaring a for loop
    int i=0 means we declare a variable. This is done before we start looping
    i<3 means we will loop as long as i<3
    i++ means that for every loop we do i++ (as the last thing in the block)
    { defines the start of the block to be executed in each loop
  2. printf("Hi there!"); outputs "Hi there!"
  3. } closes the block to be executed in each loop.

Slightly more formally we can say that an if statement looks like this:

1 for (INITIALIZATION; CONDITION; CHANGE) {
2     /* the code to execute for each loop */
3 }
  • INITIALIZATION declares a (local to the for block) variable and initializes it to some start value. This is executed only once.
  • CONDITION is the check of a boolean expression - typically a conditional expression involving the variable
  • CHANGE is what should happen with the variable every iteration - the change ensures that the condition will be false at some point so that the looping stops

Videos

  1. for (eng) (sv) (download presentation) (The presentation and video are based on Java but will do fine here)

Exercises

  1. Look at the code below
    for (int i=0; i<3; i++) {
    
            set_color(RED);
    
        }
    
    How many loops will be executed?
  2. Look at the code below
     for (int i=0; i<1; i++) {
    
        set_color(RED);
    
    }
    
  3. Look at the code below
    for (int i=0; i<0; i++) {
    
        set_color(RED);
    
    }
    
    How many loops will be executed?
  4. Look at the code below
    for (int i=3; i>0; i--) {
    
        set_color(RED);
    
    }
    
    How many loops will be executed?
  5. Look at the code below
    int counter=0;
    
    while (counter<3) {
    
        printf("Hello");
    
        counter++;
    
    }
    
    Rewrite the code above to a for-loop.


Solutions

Expand using link to the right to see the full content.

  1. Let's calculate.
    The loops starts with i=0, which is less than 3. One loop so far. After that loop, i is incremented (i++).
    Next loop i=1. Still less than 3. One more loop, so 2 loops in total. After that loop, i is incremented (i++).
    Next loop i=2. Still less than 3. One more loop, so 3 loops in total. After that loop, i is incremented (i++).
    Next loop i=3, which is NOT less than 3, so we're exiting the loop.
    3 loops in total.
  2. 1 loop.
  3. 0 loops
  4. 3 loops.
    First loop i=3, which is bigger than 0. Decrease i. One loop so far
    Next loop i=2, which is still bigger than 0. Decrease i. Two loops so far.
    Next loop i=1, which is still bigger than 0. Decrease i. Three loops so far.
    Next loop i=0, which is NOT bigger than 0. .... loop is exited.
  5.   for (int counter=0;counter<3;counter++) {
    
        printf("Hello");
    
      }
    
    You can also download source code with a suggested solution: For.java

Links

misc

Description

There are some more control flow constructions, apart from if, while and for. We will go through these quickly in this presentation. In this book, we use the C programming language and the only available control flow statements in C are:

Choice/decision making: (if-then, if-then-else, switch), looping/iteration: (for, while, do-while), and branching statements: (break, continue, return)

This chapter focus only on the following: if-then, if-then-else, for, while.

Videos

  1. Misc (eng) (sv) (download presentation) (The presentation and video are based on Java but will do fine here)

Exercises

There are no exercises in this chapter section.

Solutions

Expand using link to the right to see the full content.


Chapter Links

Our C FAQ

External links

Books this chapter is a part of

Programming with C book

Book TOC | previous chapter | next chapter