# Programming 101 Part 2 — Decision Making and Flow Control

Posted by & filed under Tech Geek.

In Part 1 of this series about computer programming for beginners, we examined a simple program that added two numbers together and printed out the results, which isn’t all that useful. If we think back to the tire changing example, the steps we wrote are far from complete. We have to remove multiple lug nuts and it would be nice to use the same instructions for each lug nut. This is something referred to as a loop… executing the same code multiple times.

Normally loops should stop at some point, after all you run out of lug nuts. Loops that do not finish are called “Infinite Loops” and are generally considered bad for programming. Occasionally a programmer will want to have a loop that doesn’t terminate on purpose for programs that don’t end, though even though the loop itself doesn’t end, the program would repsond to some control that would force the program to exit properly.

Your programs will sometimes need to make decisions based on some conditions. You have to see if the tire is flat before changing it.

• Is the front-driver side tire flat?
• Yes: Change it!
• No: Check the next tire

## Decision Making

Remember that Algebra II class in high school you said you would never use? Well its time to use that class…

In Lua, there is really only one decision making statement, the “IF” statement. Other languages like C support other methods, like a “Switch” statement. Lua is a “Keep It Simple Silly” language, so we really only have the one decision maker.

To make use of the “IF” statement, you have to understand basic math and “Boolean” logic operators. These operators, when combined with variables or fixed values (called “Constants”) form a “Condition”. Condition’s are also used by some of the loop controls to determine when they are to exit.

## Operators

The core mathematical operators that you need to know are:

• == which means “is equal to”
• < which means “less than”
• > which menas “greater than”
• <= which means “less than or equal to
• >= which means “greater than or equal to
• ~= which means “not equal too”

Here is an example:

``` a = 10 b = 20```

``` ```

```if a == b then print("a and b are equal") end ```

In this test we check to see if variable “a” and variable “b” are equal. If they are, the we print a message. If they are not equal then we do nothing. What if you wanted a message saying they are not equal? The “IF” statement has an additional option called “ELSE”

``` a = 10 b = 20```

``` ```

```if a == b then print("a and b are equal") else print("a and be are not the same") end ```

Or consider:

``` ```

```count = count - 1 if count < 0 then count = 0 end ```

The above example makes sure that count is never negative after the subtraction the line above. This is called range checking.

Using the above example, what if our code would also possibly add to count rather than in the example where we are doing a subtraction? We might want to make sure count never goes over a value of 10. We could write:

``` count = count + 1 if count < 0 then count = 0 end if count > 10 then count = 10 end ```

Here we wrote the if statement twice. But we could do this more efficiently by writing a more complex condition. This is where the "Boolean" operators come into play. They are:

• condition 1 AND condition 2
• condition 1 OR condition 2

When the computer or device looks at the conditions like "count < 0", it evaluates to either "TRUE" or "FALSE". If count is less than 0, then that condition is TRUE. If it is not, it is FALSE. This is computers at their very basic, they only know 1 or 0, which is the same as TRUE or FALSE. We could rewrite our code like this: ``` count = count + 1 if count < 0 or count > 10 then print("count is out of bounds") else print("count is in bounds") end ```

This could have also been written:

``` count = count + 1 if count >= 0 and count <= 10 then print("count is in bounds") else print("count is out of bounds") end ```

For the AND operator, both conditions have to be TRUE before it will be treated as TRUE. In the case of the OR operator, if either condition is TRUE, then the whole statement is treated as TRUE.

There is also a NOT operator which will negate tests. In other words: NOT TRUE == FALSE and NOT FALSE == TRUE. As someone learning programming logical operators can be challenging.

## Looping

Using an IF statement is a type of flow control known as "Branching". You test a condition and based on the result you go along one of two paths, like coming to a fork in the road. The condition is the "Decision Making" part of this: Do you go down the left fork or the right fork? Once you've decided and move on, you've now changed the flow of your program and different statements will execute.

Branching is only one type of flow control, the other is looping. Let's use an Indy Car race as an example. You're in Indianapolis on Memorial Day and you're racing in the Indy 500. It's a 500 mile race on a 2.5 mile track, so you are going to make 200 laps during the race.

As a driver you have to make many decisions during the race, but we are going to focus on two:

1. Do I need to Pit Stop?
2. Is the race over?

The first example, "Do I need to pit?" is a branching statement. If you do, you slow down, stop in your pit box, get new tires and some fuel and then resume the race, else you blast by the grandstand at 235mph. I know we covered that above, but good thinking. That is an IF statement.

But if you think about the race as a whole, its nothing but a series of 200 loops. Execute several left hand turns, passes, breaking etc. and come around to the start/finish line and ask? Have I run 200 laps yet? No, repeat the whole loop again, each time incrementing your lap counter. Pass the start/finish line again? Have I run 200 laps yet? No, keep going, yes head to victory lane if you're the winner (see an other Branch in the program, not the winner, go to the garage).

In programming languages we manage these loops with one of three main looping structures:

• WHILE condition is true DO some block of code
• REPEAT some block of code UNTIL condition is true
• FOR some set number of iterations (laps!) DO some block of code

Using our race as an example of a WHILE loop (WHILE condition DO block END):

``` ```

```lapCounter = 0 while lapCounter < 200 do lapCounter = lapCounter + 1 end print("The race is over") ```

A while loop will execute over and over until it's condition becomes false, in this case, it will run 200 times. Since we are starting at 0, when we hit lap 199, we will have looped 200 times in actuality since lap 0 counts as a lap in this case. We come around and add one more to lapCounter and it becomes 200. The condition becomes true (200 is not less than 200) at which case the loop ends and we execute the next statement after the loop, in this case the print.

REPEAT block UNTIL condition is very similar to a while loop, but we test at the end of the loop rather than at the beginning:

``` ```

```lapCounter = 0 repeat lapCounter = lapCounter + 1 until lapCounter = 200 print("The race is over") ```

You will notice the condition I tested for is different between the REPEAT and the WHILE loop. There are two very fundamental and important difference between the two loops.

First, A REPEAT loop is guaranteed to run at least once. With the WHILE loop example, if lapCounter had started at 300 then 300 is greater than 200 and the WHILE loop would never execute. With REPEAT we don't test until we've done the block's code (at the end of the loop instead of the beginning of the loop) and as such, lapCounter gets incremented before we test it, so instead of counting our loops 0 to 199 in the WHILE, we are going to end up counting 1 to 200 in the REPEAT example.

Secondly, a WHILE loop continues while the condition is TRUE. A REPEAT loop continues while the condition is FALSE.

What happens if the condition to exit the loop never happens? This is what is know as an "Infinite Loop". While there are some rare occurrences where it makes programming sense to have a loop that never ends (actually all loops end... the computer will eventually be shutdown..... and the operating system will exit the loop for you!), most of the time these never ending loops are a bug*.... a programmer's mistake.

### The first computer bug...

was actually a physical bug. A moth got into the computer core and shorted out the vacuum tubes that ran the program and crashed the computer. The term "bug" stuck for any problem that affects the proper execution of a program...

And its a mistake you should avoid as it generally will lock up your application and you have to use the operating system to force kill your program.

FOR loops are the third type of looping and they may be the most useful since they count over a fixed number of iterations:

``` for lapCounter = 1, 200 do -- do the stuff for each lap here end print("The race is over") ```

In this example, the loop itself manages the lap counting for us. We tell it a starting lap number and an ending lap number and it will execute that number of times, in this case, 200 times since we started at 1.

You will frequently (and I do mean very frequently) see that loop written like this:

``` for i = 1, 200 do -- do the stuff for each lap here end print("The race is over") ```

Where did the "i" come from and what does it mean? Well "i" is shorthand for "index" which is basically a variable that keeps track of the number of times we have gone through the loop. In days of old, there was a popular language called BASIC (Beginners All-purpose Symbolic Instruction Code) which is very similar to Lua in many respects, but the rules for BASIC said all variable names were exactly one letter long. You only had 26 bins to store things in (A thru Z) and I became popular for the for loop index. And that has stuck with programming through out the years.

FOR loops may be the most popular looping structure because you generally know how many times you want to run. Need to create 10 blocks on the screen? A FOR loop is perfect for that:

``` for i = 1, 10 do block = createBlock() end ```

and volia! You have 10 blocks.

There is a second variant of the FOR loop that uses key-value pairs to iterate over a table of values, but it's difficult to talk about that until we have covered Arrays, Tables and Objects in Part III of this series.