Decisions, Structures, Logic

Read time: 35 minutes (8877 words)

See also

Text: Chapter 4

Back in Input - Process - Output we saw three basic programming tools that all programmers use. These are called the “structures” of programming. Only three are needed, but we use variations of some of them for convenience!

In that lecture, we started exploring using these tools to solve a checkbook balancing problem. Let’s try another problem, and see how we use the tools in more detail. Once again, we will use “pseudo code” to do our thinking.

Reviewing Pseudo Code

Remember that there are no formal rules for pseudo code. Your pseudo code starts at the top, on that first line. In some notations, we would put the word START there to show where we start. Where do you stop?

The right answer is at the end of the code. A properly structured program always ends at the bottom, not in the middle somewhere.

Approaches to Design

How you think through the solution to a problem is something you have to decide. There are two basic approaches:

Top Down

We should work on our logic to make sure we have a proper way to start work, and a proper way to stop work. You can use this “top-down” approach to building any program. You start off by looking at the big picture and work your way down to the details. That is essentially how I did things here.

Bottom Up

Another approach is to work “bottom-up” where you start with details and build up to a complete program. For beginners, it makes more sense to work top-down as we did in the checkbook example.

Structures seem to impose rules on you, and some folks balk at that. “We don’t need no stinking rules!” Well, in some circles that may be true, but in programming, it has been shown over and over, that humans build better programs, and get more accurate results if they follow the simple rules of structured programming. As you do more of this, I believe you will see that!

Indenting

Along with structures, programmers started doing something else when they converted their diagrams to real code. They started “indenting” things. Do you see how indenting makes it more obvious what part of the pseudo-code is happening during the true part or an IF-THEN-ELSE structure, and what part is happening during the false part? Indenting is an important part of programming, even when using languages that do not really care about things like that.

A simple fact of life in programming is that humans read programs far more than computers do. It is important to make your code “readable”, and each language has a preferred style for how things should be presented. In today’s world of programming, indenting is done with exactly four spaces (not tabs) and folks will look at you funny if you do otherwise. You are not really writing a program for yourself, most of the time. It is for the poor soul who will have to maintain that program long after you have moved on. Surprisingly, that may be you in a few months, when you have forgotten that you even wrote this thing!

Another Problem to Solve

Let’s try to solve another problem using some real code!

How about a programmable thermostat. (I am sitting in my living room looking around for a problem to try out! It was there, on the wall, just staring at me!)

Here is a problem statement:

Write a program for a thermostat with two buttons: one to increase the temperature, and one to decrease the temperature. The thermostat has a temperature sensor that can report the current temperature, and a display showing the temperature we want the house to have. The thermostat can turn on the heat, or the air conditioner.

Sounds simple enough. What structures do you see here. Is there a loop, is there a decision to make, is there input? Is there output? Phew, that is a lot to consider.

Once again, use your own sense of what has to happen to see what needs to be done by our program.

Just for fun, rather than use our pseudo-code again, I will show you a Python program that might do this job:

# Thermostat program

# This program assumes that several modules are available to deal with
#   human interactions:
#
#   currentTemperature()     - reads the current temperature sensor
#   ActivateHeat()           - turns on the heat
#   ActivateAirConditioner() - turns on the air conditioner
#   ButtonUpPressed()        - is the user holding down the up button?
#   ButtonDownPressed()      - is the user holding down the down button?

currentSetting = currentTemperature()
while True:
    if Temperature() > currentSetting:
        ActivateAirConditioner()
    elif Temperature() < currentSetting:
        ActivateHeat()
    If buttonUpPressed():
        currentSetting = currentSetting + 1
    if buttonDownPressed():
        currentSetting = currentSetting - 1

Those lines beginning with a sharp character are comments, ignored by the language. Everything else is code.

Note

Python is a language that requires the use of indenting to show the structure of the program. That “while True:” line is a while loop and everything below that line is indented. That means that all code indented below that point is inside the loop. There are structures inside other structures here, and the code for those inner structures is indented more.

When will this loop end? Never! I do not want my thermostat to take a vacation!

Asking Questions (Decisions)

We always need to ask questions in our programs. We need to know what is going on, so we examine the data to find out.

All questions in programs have answers that are either “true” or “false”. No “maybe” allowed.

We call these questions “boolean”, and we can ask complex questions as long as they end up producing “true” or “false” only.

Boolean Expressions

Expressions are those constructs that have to be “evaluated” to produce a final value. Math expressions are the most common:

  • 4 * a + b

In this expression, we are supposed to look up the value stored in the containers “a” and “b”, and evaluate the result of doing this math! The expression will generate a final value that is a number (integer). (See chapter 2 for details about how this works. We will explore math in a later lecture.)

When we ask questions in our programs, we will set up similar expressions, but the evaluation will not result in a number, it will result in a value of “true” or “false”. Those are “boolean expressions”

Relational Operators

We have several questions in our example code, and we are using notation called “relational operators”:

  • “>” means “is greater than”
  • “<” means is less than”

These are used to form statements that are either true or false.

There are other “relational operators” available:

  • “>=” means “is greater than, or equal”
  • “<=” means “is less than, or equal”
  • “!=” means “is not equal to”

The “NOT” operator

In working with boolean expressions (those formulas that end up giving “true” or “false” results), we can use the “NOT” operator to flip them around. “not true” is false!

Most languages also provide a “NOT” operator. In c++ the operator is the exclamation point, so this works:

  • “!(a > b)” means “is ‘a’ less than or equal to ‘b’?”

Do you see why? If “a > b” is false, then it must be that “a is less than or equal to b”. That is the opposite of “>”, not just “a < b”. What if they are equal?

In any case, using the “not” operator (“!”) turns the answer around. Why use these is up to you to decide. I seldom make my questions weird, preferring to make the question as clear as I can!

More Complex Questions

We often want to ask more complex questions.

The AND Logical Operator

A common question asks is a number falls between two values:

  • Is A between 5 and 10?

Here is a C++ expression that might do the job:

  • (A > 5) && (A < 10)

Note

I am using parentheses to avoid confusion here. The expression would work fine without those, but we need to study expressions more to see why.

Notice I used a weird operator: “&&”. Read this operator as “and”, a logical operator.

That means this expression is equivalent to this sentence:

  • “A is greater than 5, and A is less than 10”

That sentence is either “true” or “false”.

Does it do the job? That depends on if the values 5 and 10 are allowed. In the expression above, ‘A’ cannot take on either of these values. If you meant for those to be included as legal values, you should have written this:

  • (A >= 5) && (A <= 10)

There is another logical operator we can use:

The OR Logical Operator

What values for “A” could we have to make the following question “true”?

  • “A is greater than 5, or A is less than 10”

Think about it. Is a value of -100 greater than 5? No? Is it less than 10? It is! The logical operator we used here is “OR”, meaning either part can be “true” to give a true result. So this boolean expression is “true” for any value of “A”. Probably not what we wanted!

In C++, the expression would look like this:

  • (A >= 5) || (A <= 10)

It still is not a good expression, and might be a mistake! Beginners often make this mistake when building their first logical expressions!

This expression would be OK, though:

  • (A > 10) || (A < 5)

This expression will evaluate to “false” for any value between 5 and 10, inclusive! It will be “true” for any other values.

That is enough of an introduction to logical expressions to get you started. Let’s take a last look at our sample program:

Is Our Program Complete?

Left unsaid in this program is the fact that turning on the heat will make the temperature go up, and turning on the air conditioner will make the temperature go down.

Study this and see if you think it will do the job. (It won’t, by the way!) Can you make out what will happen, even though you do not know anything about

There are a few modules included here that are not shown, and those deal with reading the stuff from our human world. We test to see if a button has been pressed and use that to increase or decrease the current temperature setting.

Make sure you see the problem with this logic. It should come to you with a bit of thought. You should also see a simple solution to the problem with a bit more thought. If you do not see it, email me and I will tell you what I see!