Programming Basics for Duncan IV: Subs and Functions

In programming you’ll find that you want the computer to do the same thing again and again, usually something pretty basic. Early on, programmers decided that they didn’t want to write the same instructions again and again so they developed subroutines and functions.

A subroutine is a snippet of code that you can abstract so it can be used again and again. It can be dead simple like this one that makes the computer beep, twice:

SUB BeepTwice
BEEP
BEEP
END

You write this at the start of the program, so later when you use it the computer knows what to do.

SUB BeepTwice
BEEP
BEEP
END

CALL BeepTwice

This is handy if you want to summarise a bit of complicated code that does one thing, like advance the paper in a printer or turn a light on, but it’s not very flexible. It would be better if we could get it to do things depending on values/variables. We can pass parameters to the subroutine so it can make decisions. That looks like this:

SUB FireAlarm (isHouseOnFire)
IF isHouseOnFire = true THEN
do things that sound the alarm and turn on the sprinkler system
END

CALL FireAlarm(x)

Now we are getting somewhere! We can make loops that call subroutines instead of writing out the same code over and over. This is a powerful tool. But what if we don’t want the subroutine to do something but to do a calculation or give an output? That when we call it a function. Functions are borrowed from maths, again, and they take in parameters and give back a result when they are done. This result is always a value. Here’s a simple example:

FUNCTION add(x, y)
return x+y
END

add(5,5)

The result is 10. Functions are useful because they give you a result of some type, even if that result is a confirmation that everything worked as expected. These days people only use functions, not subroutines. With functions you can abstract your code to be more understandable, so that complex things are hidden away like:

IF getTemprature(“kitchen”) > 100 THEN FireAlarm(true)

If you wrote out the logic for all these things that are hidden away in the function then it would be a big, long mess. This one-liner is very easy to understand what’s going on.

Programming Basics for Duncan part III: If and Loops

Your most basic and common decision-making statement is the if command. It always takes this form:

IF (some test that returns a boolean true/false) THEN (do something)

So you have a test and a something(s) to do if the test resolves to true. This is where we use the comparitors from last chapter:

IF x=5 THEN do something

Almost all languages also have an else option in the if.

IF x= 5 THEN do this thing ELSE do the other thing

And that’s pretty neat! We can write a program that can think about things and do different things depending on the outcome of a test. Remember, we can use lots of comparisons like =, <, > and so on.

But life gets complicated when you have to test many values at once, you end up with ifs inside ifs like:

IF x=5 THEN IF y=0 THEN do something ELSE if y=10 THEN do that thing ELSE do something else

That gets really confusing really fast. To make life easier we use…

Boolean Logic

As well as the normal operators like = or < or => you can use logical operators. There’s a bunch but people really only use three:

  • AND: do two comparisons and if they both resolve to true, the result is true.
  • OR: do two comparisons and if either are true, the result is true.
  • NOT: is a tool to invert a result of a comparison, like NOT x=5 resolves to true if x is any value except 5.

You can combine these to make a decision like:

IF x=5 AND y=0 THEN do the thing.

Brackets (Parentheses)

Like in maths, we use brackets to say which order we want to perform operations. In programming, they’re not really used to do maths but they are really important to compartmentalise clauses in Boolean logic. It lets you make complicated comparisons like:

IF (x=5 AND y=o) OR (x=5 and y=1) THEN do the thing.

These will let you build up complicated comparisons or tests but it’s not a great idea to do so as it makes your code hard to read and other programmers will think you are just trying to show off.

Now that we have a robust way to use if we can use it in another time-saving tool, loops.

Loops

A loop lets us do the same thing over and over again. My first ever program when like this:

10 PRINT “Hello World”
20 GOTO 10

This would output Hello World to the TV forever, until you hit the STOP key on my VIC20 and my friends and I were deeply impressed. We don’t use GOTO anymore and it’s considered gauche and very uncool.

But the idea of doing something again and again, or more usefully, a set number of times is called a loop. At the most basic they do this:

DO something
IF test is true THEN STOP ELSE GO BACK TO DO

All loops are like this, although most put the test first. The most common type is a FOR loop and it usually includes a counter often called an index and written i.

So you set i to 0 or 1 (normally) and you make a test to check the value of i each time the loop loops:

i = 1
IF i=5 THEN STOP
do something
i = i+1
GO BACK TO THE IF STATEMENT

It’s normally written:

FOR i=1, i=i+1, 5
do something
NEXT

Or some variation on that scheme.

This will ‘do something’ four times and the final value of i will be 5. FOR statements are the bread and butter of programming as they will let you count things, look for things over and over.

The other type of loop is a WHILE

WHILE NOT i = 5 THEN
do something
i=i+1
LOOP

That does the same thing as our FOR loop but you can use it when you don’t know how many times the look is supposed to run. You can do it without and index like

WHILE NOT y=”finished” THEN
do something
LOOP

That loops until y is set to the string “finished”, maybe forever.

So now we can do maths, do things with words, make tests and loop the same bit of code until a certain time or number of repetitions. For lots of (old) languages, that would be it. But we need one more chapter to cover the basics.

Programming Basics for Duncan part II: Primitives

It’s fun to call them primitives because it makes you feel smart but what we are talking about are the most basic things in a program.

Values

The most basic thing in a program is a value. It is what it is. It can be a number, 5 if my favourite, a letter like K or k or perhaps a decimal like 0.7. Or maybe a boolean value like 1 or 0. It is only one thing. It is a single answer to a question. It is not a word, those a strings, which is a list of values.

Variables

Variables are placeholders for values and they are borrowed from maths, algebra to be exact. So ‘x’ in a maths formula is a variable. It is a label for a value that we don’t necessarily know at the time. Think of it as an envelope with a name written on it.

Types

Variables and values can be of different types. Here are some normal types:

  • Integer: a whole, positive number, like 5. It could also be a negative number, depending on your language.
  • Floating point, or Decimal: like 18.2.
  • Character: a letter, like K or k.
  • String: a collection of characters, in order, like I like Ike. They are usually written in quotes, to make it clear that you are typing a string, not a command. So, “I like Ike”.
  • Boolean: Yes/No, True/False, 1/0. There can only ever be two values and these are used for making decisions.

Programming languages can be divided into those that are strongly-typed or loosely-typed. In a strongly-typed language you have to tell the computer what type each value or variable is in advance, or you get an error. In a loosely-typed language you can just write stuff and the computer will usually guess the type correctly.

Operators

Now we have a value, a variable to store it in and we know what kind of value it is. To do anything with it, we use an operator. Operators are the most basic commands and they do basic things. At their most basic, we have arithmetic. These are the same in almost all languages:

  • + is plus (or sum)
  • – is minus (or difference)
  • * is multiplication
  • / is division
  • % is modulus, but don’t worry about that for now.

Each operator appears between two values or variables, like x + 1, usually integers or decimals, and they give the arithmetic result, another integer or decimal. Then we have comparitors, which compare values.

  • = checks if two values/variables are equal .
  • == checks if two values/variables are the same, not the same thing as equal, but you don’t have to worry about that at the moment. I’m just putting it in to keep you alert.
  • > Greater than.
  • < Less than .
  • <= Equal to or greater than.
  • >= Equal to or less than. These all work great for integers or decimals, but get odd results for characters or strings.

All these comparitors need two values or variables to check. Like is x = 5. The result isn’t a number, it’s a boolen, which we usually think of as true or false.

So now we can do maths and compare things, there’s one other kind of operator, string operators:

  • = checks if two strings are the same. This can be really tricky. Is the integer 5 the same as the 5 in “I have 5 donkeys.”? Some languages say yes, some say no because the values are different types. This is a really, really common difficulty in programming and is why we have strongly-typed languages in the first place.
  • + or & is used to add strings together, or we say concatinate two strings. What it does is glue the second string to the end of the first string.

Did I say one other kind of operator? There’s one more and it’s a big one. Assignment.

To assign a value to a variable we normally use an equals sign. In the old days they would use the command Let, which is borrowed from maths:

Let x =5

This tells the computer that you are declaring a new variable, x, and assigning it the value 5. If you want to change the value later you write:

x = 9

These days most languages will let you just write this at the start and it will automatically create the variable x when you first assign a variable to it.

So now we can do things with maths and with words (strings). If you add If statements you have enough to write any program. The trouble is that your program would be really long and repetitive. All languages have other commands to make life easier and more rational.

Programming Basics for Duncan Part I: Hello World

The classic first program on any platform is to output the string “Hello World”. Hang on, string? Yes, it’s a string of characters: H-e-l-l-o-space-W-o-r-l-d. Technically, it’s an array but you don’t need to know about that now.

The other thing you need to print Hello World is a print command. This may be PRINT “Hello World” in BASIC, which nobody uses anymore or printf(“Hello World”); in C, which few people use anymore.

But it’s a good teaching example of a very, very simple program. A command and some data that interacts with the human operator (you) probably via a screen. In the old days it would have been printer and paper.

To make a Hello World program, it depends on which platform you’re using. There are roughly two types: Programming platforms and languages where you need to set up an environment, a project, include libraries and do loads of other work just to get to Hello World. The other is scripting environments, where a lot of the stuff in programming environments is already done for you and you can type things in and run them immediately.

I recommend the latter so we can get to Hello World quicker. If you are reading this in a web browser, I don’t know how else you would, hit the F12 key to open the dubugger. There will be a tab called Console which gives you a basic command line. Type:

console.log(“Hello World”);

This should ‘log’ (output) a line to the console, the command prompt you are tying on. You can see that there’s lots of punctuation on this line and that’s all needed to satisfy JavaScript’s syntax. Getting the punctuation and spelling right is the first thing you need to do or you get syntax errors and these are the most common errors you will get. You will get mostly errors when you program and most of programming is fixing errors.