Programming Basics 5 – Control flow

Introduction

This part will teach you, how to compare values and control the flow of your program. It will also teach you, how to repeat a part of your program for a defined number of times, which is very useful for tasks like processing user input or printing out data.

This is a very long article. I didn’t plan to make it this long, but I ended up writing a lot about this topic. I recommend you to split it into half after the ‘Large choices’ section and take a break. However, let’s get started!

Solution to the last exercise

The exercise was:

Warning: Advanced exercise! Try to solve it, without looking it up in the next part of the series or anywhere else, I’ll explain the solution in the next part, but It’ll help you a lot to understand the topic, if you do this exercise on your own. However don’t be upset, if you can’t solve it. It’s intended to be a hard exercise!

Arrays can hold every type of object or primitive variable. So an array can also hold another array, which will create a so called multi-dimensional array. Try to do that!

Try to create an array that holds integer arrays! Instantiate both with a length of five fields and try to read to and write from the integer arrays!

Hint: Look at the syntax section and read the last two sentences, it should be easier to think of the right syntax for multi-dimensional arrays!

Okay so basically you wanted to create an Array-array, a so called multi-dimensional array. If we take a look at the syntax, described in part 4, you should get the idea of a multi-dimensional array:

(access_mod) field_type[] array_name = new field_type[array_length];

Now we create an array:

 private int[] myArray = new int[10];

Now if we use an Array (for instance a float[]) instead of the int-type, we get a multi-dimensional array:

private float[][] multidimensionalArray = new float[5][5];

There we go. We created an array that contains five float-arrays (which also have a length of five). Like I said in part 4, you can imagine an array as a box for chocolates. In the last part our box had one row to store chocolates in. Now we added columns to the rows, so we can store elements in a different fashion. I know, this might sound very confusing at this point, we’ll get back to this topic when we discuss more advanced and dynamic data types.

Conditions and comparisons

In part 2 of the series, when we looked at primitive datatypes, you saw the boolean datatype. This type is used to store a state. It can either be true or false, nothing in between that.

True or false are always the result of a condition. For example if you compare two whole numbers like 5 and 2, what can you say about them? Both are greater than zero, both are less than ten, two is less than five and five is greater than two (Which is basically the same statement, just reversed).

Let’s form these examples into mathematical statements:

5 > 0
2 > 0
5 < 10
2 < 10
2 < 5, alternatively 5 > 2

All of these statements are true. You can now take the result of a comparison and save it into a boolean variable:

//statement will be true
private boolean statement = (5 > 0);

// lie will be true
private boolean lie = (0 > 42);

You can use all kinds of so called relational operators. Here is a short list of operators in Java (for a complete list of all operators, refer to this article):

Operator Meaning Example
== equals (Physical equality) a == b
!= unequals a != b
< less than a < b
> greater than a > b
<= less than or equals to a <= b
>= greater than or equals to a >= b
equals equals (Structural equality, used for comparing objects) a.equals(b);

All operators evaluate to boolean values (true or false). But how can we use them in our program? You can check variable values in your application and control your program to do something based on the result of the check. This is done with so called if-statements.

If-statements

With if-statements you can evaluate boolean values. If they are true, the code inside the if-statement’s body will be executed, otherwise not:

if(5 < 2)
{
    System.out.println("The cake is a lie!");
}

Obviously, the line is never being printed out, because five is greater than two. If you want your program to take an alternative path, if your if-statement evaluates to false, you can use the else-block right after the if-block:

if(5 < 2)
{
    System.out.println("The cake is a lie!");
}
else
{
    System.out.println("There is cake in the fridge!");
}

The syntax of the if/else-statement is as follows:

if(boolean_value_to_evaluate)
{
    // Do something if the condition is true
}
else
{
    // Otherwise do this
}

Combining comparisons

If you want to check multiple values, or a range, you can combine comparisons. For example if you want to check if a value is greater than zero and less than 100, you can do the following:

boolean result = value > 0 && value < 100;

Like I said earlier, comparisons always result in a boolean, therefore the following line of code is also valid:

// result will be false
boolean result = true && false;

There are the following operators:

Operator Meaning Example
&& logical and a && b
|| logical or a || b
! inversion !(a && b)

Please note that the and-operator and the or-operator are the same character repeated twice. This is not a typo. The single ampersand (&) and the single pipe (|) are bitwise operators, so don’t confuse them with the logical operators. Also note that in Java numbers are not recognized as booleans natively. In some other languages 0 means false and everything greater than 0 means true, in some other languages 0 is false, 1 is true.

For a complete listing of operators, you can visit this page.

Large choices

Imagine the following problem: You display a menu to the user of your application. The main menu has several options, one can choose from:

bildschirmfoto-2016-09-14-um-15-08-56
Figure 1: An application’s main menu

Of course you could just read the user’s input and then check it with a lot of if and else statements:

if(input == 1)
{
    loadVideo("cat");
}
else
{
    if(input == 2)
    {
        makeSandwich("ham", "cheese", "tomatoes");
    }
    else
    {
        if(input == 3)
        ...
    }
}

But that’s a nasty way of doing this. It doesn’t only look bad but it’s also slow. A much cleaner result can be achieved by using the so called switch-case statement. It is useful to check the state a variable, that can have more than two states, has:

// input is an integer
switch(input)
{
    case 1:
    loadVideo("cat");
    break;

    case 2:
    makeSandwich("ham", "cheese", "tomatoes");
    break;

    case 3:
    ...

    default:
    askAgain();
}

As you can see, this method looks way cleaner and is easier to read and maintain. The program will loop through each case until it finds the (first) correct one. Note that I wrote the break keyword at the end of a case-block. It is not necessarily needed, but recommended. It is used to leave loops and statements before they finished execution completely. If it were not at the end of a case-block, the program would go on checking the other case blocks as well, which wouldn’t make any sense. Therefore you should end a case block when you are done. Note that you can end it on different ways, like using the return statement instead of break, however this will obviously also leave the method the switch-statement is written in.

As you can see,  I added a default-case at the end. This is not mandatory as well, but recommended. It acts like the else-block: If none of the above cases matches the input, some default action is being executed. In our case, the user is prompted to input the number again.

Loops

Loops are used for executing a specific piece of code over and over again, without having to write it multiple times. This can be very useful for repetitive tasks like filling arrays or printing out many values.

Basically there are two types of loops: count controlled and condition controlled loops. We’ll start with a count controlled loop, the for loop:

for(int i = 0; i < n; i++)
{ /* Do something */ }

A for loop is used to repeat a process n times in a row. As you can see, a new integer variable, called i in this case, is declared and initialized in the loop’s head. Note that this variable can only be a whole number. This is due to the imprecision that occurs when the cpu rounds floating point numbers. The declaration is then followed by the loop’s condition. The code in the loop’s body will be executed, as long as this condition is true (so it’ll be executed n times in this case). Afterwards, the so called afterthought is declared in the loop’s head. This operation will be executed each time, the loop goes from one iteration to the next, which usually happens after the code in the loop’s body has finished executing.

However, a loop’s current iteration can be skipped with the continue keyword or the loop can be left earlier with the break keyword.

This leads us to the following syntax:

for (INITIALIZATION; CONDITION; AFTERTHOUGHT) 
{
    // Code for the for-loop's body goes here.
    // Use break to leave the loop immediately
    // Use continue to skip the current iteration
}

Now we jump right into condition controlled loops. So here it comes, the while loop:

while(application_running)
{
    // do something

    if(user_input == "exit")
        application_running = false;
}

The above example is actually quite easy to understand and so is the while loop. Anything that is inside the loop’s body will be executed as long as the loop’s condition is true or the loop is not exited with the help of a return or break operation. The condition can be any boolean. There is a second type of while loop:

do
{
    // do something and read user input
}
while(user_input != "exit")

This is basically the same thing as above, but with this type of while-loop you can guarantee that the code in the loop’s body is at least executed once. In the first while-loop the condition could be false before the loop is entered and therefore the code inside the loop will never be executed.

Exercise

There is no specific exercise this time. You’ve earned yourself a break after this long post. However you may experiment with loops and conditions. For example you could try filling an array with numbers from 0-99 and then print these numbers to the console.

See you in the next part!

Table of contents

Part 1 – MyFirstProgram
Part 2 – Access Modifiers and Variables
Part 3 – Methods
Part 4 – Arrays
Part 5 – Control flow (You are here)
Part 6 – Classes and Objects
Part 7 – Exceptions and exception handling

comment-banner

Advertisements

11 thoughts on “Programming Basics 5 – Control flow

    1. No you forgot to tell the program what index of the array should be set. You can not assign a integer value to an array directly, you have to tell the array on what index the integer should be assigned:

      for(int i = 0; i < array.length; i++)
      { array[i] = i; }

      Never forget the index!

      Liked by 2 people

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s