Never confuse education with intelligence, you can have a PhD and still be an idiot.
- Richard Feynman -



Chapter:Control flow

From Juneday education
Revision as of 10:13, 13 September 2016 by Henrik Sandklef (Talk | contribs) (Videos)

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)

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) {
  System.out.println("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) {
  System.out.println("Please, turn on the fan");
} else {
  System.out.println("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) {
  System.out.println("Please, turn the fan to MAX.");
} else if (temperature>30){
  System.out.println("Please, turn on the fan modestly");
} else {
  System.out.println("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)

Exercises

  1. We have the following code:
    if (nrOfStudents>90) {
    
        bookBigRoom;
    
    } else {
    
        bookMediumRoom;
    
    }
    
    a) let’s pretend that the number of students, reflected in the variable nrOfStudents, are 123. What [statement] is reached?
    b) let’s pretend that the number of students, reflected in the variable nrOfStudents, are 90. What statement is reached?
    c) let’s pretend that the number of students, reflected in the variable nrOfStudents, are 89. What statement is reached?
  2. We have the following code.
    if (nrOfStudents>90) {
    
        bookBigRoom;
    
    } else if (nrOfStudents>20) {
    
        bookMediumRoom;
    
    } else {
    
        bookSmallRoom;
    
    }
    
    a) let’s pretend that the number of students, reflected in the variable nrOfStudents, 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 (nrOfStudents>90) {
    
        bookBigRoom;
    
    } else if (nrOfStudents>20) {
    
        bookMediumRoom;
    
    } else if (nrOfStudents>0) {
    
        bookSmallRoom;
    
    }
    
    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) {
    
                System.out.println("Wow, you're over hundred years old!");
    
            } else {
    
                System.out.println("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) {
    
                System.out.println("Wow, you're over hundred years old!");
    
            } else if (age>80) {
    
                System.out.println("Wow, you're kind of old!");
    
            } else {
    
                System.out.println("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) bookBigRoom
    b) bookMediumRoom
    c) bookMediumRoom
  2. a) bookBigRoom, since 123 i greater than 90
    b) bookMediumRoom, since 90 is not greater than 90 but greater than 20
    c) bookMediumRoom, since 89 is not greater than 90 but greater than 20
    d) bookMediumRoom, since 21 is not greater than 90 but greater than 20
    e) bookSmallRoom, since 20 is not greater than 90 nor greater than 20
    f) bookSmallRoom, since 5 is not greater than 90 nor greater than 20
    g) bookSmallRoom, since 0 is not greater than 90 nor greater than 20
  3. a) bookSmallRoom
    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   System.out.println("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)

Exercises

  1. Look at the code below.
        while (true) {
    
          setColor(RED);
    
        }
    
    How long does it execute?
  2. Look at the code below.
        while (false) {
    
          setColor(RED);
    
        }
    
    How many loops will be executed?
  3. Look at the code below.
        int counter=0;
    
        while (counter<3) {
    
          setColor(RED);
    
          counter++;
    
        }
    
    How many loops will be executed?
  4. Look at the code below.
        int counter=0;
    
        while (counter<3) {
    
          setColor(RED);
    
        }
    
    How many loops will be executed?
  5. Let's assume that the method getTemperature is connected to a thermometer and that the method returns an integer value which gives us the temperature in Celsius.
        while (getTemperature() < 20) {
    
              heatUp();
    
        }
    
    Btw, heatUp is a so called method connected to a radiator which will heat up the room.
    Try to explain how the code works.
  6. Look at the following code in
      System.out.println("Hi there..");{
    
      System.out.println("Hi there..");{
    
      System.out.println("Hi there..");{
    
      System.out.println("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 method. When the room is 20 we continue with some other thing.... (the code below).
  6.   int i=0;
    
      while (i<4) {
    
        System.out.println("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   System.out.println("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. System.out.println("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

Since Java version 1.5 you can also use the so called for-each-loop in references to Iterable objects (typically collections such as ArrayList):

for (Type item : iterableReferenceVariable) {
    // Do something to item
}

An example using a list of String references could look like this:

List<String> someList = someMethodReturningAListOfStrings();
for (String item : someList) {
    System.out.println(item.toLowerCase());
}

The code above would print each String in the list with all letters in lower case.

Videos

  1. for (eng) (sv)

Exercises

  1. Look at the code below
    for (int i=0; i<3; i++) {
    
            setColor(RED);
    
        }
    
    How many loops will be executed?
  2. Look at the code below
     for (int i=0; i<1; i++) {
    
        setColor(RED);
    
    }
    
  3. Look at the code below
    for (int i=0; i<0; i++) {
    
        setColor(RED);
    
    }
    
    How many loops will be executed?
  4. Look at the code below
    for (int i=3; i>0; i--) {
    
        setColor(RED);
    
    }
    
    How many loops will be executed?
  5. Look at the code below
    int counter=0;
    
    while (counter<3) {
    
        System.out.println("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++) {
    
        System.out.println("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 Java programming language and the only available control flow statements in Java 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)

Exercises

There are no exercises in this chapter section.

Solutions

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

Questions and Answers

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

Q: “The for loop and the while loop seem to do the same thing. When should we use the one and when should we use the other?”
A: You may use the one you feel most comfortable with. If you want a hint of when to use for and when to use while, there is a recommendation that in situation when you know beforehand how many iterations you want, you should use the for loop. It could make the program easier to read and understand. When you don’t know how many iterations you want (for instance if your program is reading lines of text from a file and you don’t know how many lines there are in the file), it is probably more clear to use the while loop. When you read the code out loud, it could better match the way we think and speak. An example of reading out loud the line counting loop, could be “While we haven’t reached the end-of-file, read one more line and increase numberOfLines with one”. If we want to print ten copies of a document, we could use for and such a piece of programming could be read out loud like this, perhaps: “For every number between 0 and 9, print a copy and move the counter to the next number”.

As you see, reading out the for statement doesn’t really match the way we think or speak, but there is an alternative syntax for the for loop that we use when we have some kind of list. We’ll revisit the for loop when we have learned about lists, but as a teaser, we can say already that reading out the for loop when iterating over a list reads something like this: “For each element in theList, do something with that element and move on to the next element”.

Q: “Are there any other control flow mechanisms that you haven’t told us about?”
A: Actually, yes. There is a version of the while loop, called “do while”. It works almost like the while loop, but it always execute the statements in the block at least once, because it has the test of the condition at the end of the block.

 do{
 swingAxeAgainstTree();
}while( tree.isStillStanding() );

The example above could be a simulation of cutting down a tree using an axe. We know that we must swing the axe against the tree at least once. And then we check to see if the tree is still standing. If it is, we repeat until the test fails (and and the tree is down).

To be honest, the do while construct is not very common, since in most situation (like when cutting down trees) there is no harm in doing the test first. That would be like first checking that the tree is standing before starting to swing the axe against it.

Another construct is the Switch statement. It is useful as an alternative to if-else-if statements when we know that there are many possible cases to test. It is quite common but not very hard to learn. We will not require that you know the switch statement but we encourage you to learn it anyway, as an exercise. You can read about it here: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/switch.html

Q: “Where in a Java program do we use the control flow things?”
A: Almost exclusively in methods and constructors. There are some exceptions to that rule (there are two special kinds of nameless blocks inside classes, but they are outside the scope of this course!) but if you want a rule it would be: Always inside a block, but never directly inside the block of a class (or inside the block of the friends of classes called interfaces and enums).

So you will never see an if statement, for instance, directly in the body of the class block. It is always inside a block that is inside the class block. Remember, the class block is one of the few blocks that can be the outermost blocks in a compilation unit (in a Java source code file).

Chapter Links

External links

Read them!

Books this chapter is a part of

Programming with Java book

Book TOC | previous chapter | next chapter