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 15:02, 4 October 2017 by Henrik Sandklef (Talk | contribs) (more code to for each loop)

Jump to: navigation, search

Control flow

Meta information about this chapter

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

Introduction

TODO: write intro

Purpose

TODO: write purpose

Goal

TODO: write goal

Concepts

TODO: write concepts

Instructions to the teacher

TODO...

Common problems

TODO...

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

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)

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
}

Let's look at the following example of a classic for loop:

List<String> someList = someMethodReturningAListOfStrings();
for (int item=0; item<someList.size(); i++) {
    String s = someList.get(item);
    System.out.println(s.toLowerCase());
}

The code above would print each String in the list with all letters in lower case. Now we should do a similar thing using the for each-loop. Before you look at the code below we would like you to take special notice of the following parts of the for loop above: String s, someList and System.out.println(s.toLowerCase()).

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 also print each String in the list with all letters in lower case. You can hopefully see some similarities in the for loop above (String s, someList and System.out.println(s.toLowerCase())).

Videos

  1. for (eng) (sv) (download presentation)

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) (download presentation)

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).

Links

Further reading

Where to go next

« PreviousBook TOCNext »