Tech Tuesday: Control Structures (Cont’d)
I was originally planning to write today’s Tech Tuesday post about how we can define our own words in a programming language. But then I noticed an important omission in last week’s post on control structures. I didn’t really explain how we can have multiple statements in either a loop or in a branch of program execution. I just kind of snuck that into the following example:
var i = 1;
while (i < 6) {
alert("Counter is " + i);
i++;
}
Here we have two statements inside the loop: the “alert” and then the incrementing of the variable i. In order for the computer to know what is supposed to be part of the loop, we need some way of grouping these two statements together. In Javascript this is accomplished with the so called “curly braces” { and }
var i = 1;
while (i < 6) {
alert("Counter is " + i);
i++;
alert("Still in the loop");
}
alert("After the loop");
We refer to a group of statements as a block. Other programming languages have different ways of indicating blocks. For instance, Python uses indentation as follows:
i = 1
while i < 6:
print "Counter is" , i
i++
print "Still in the loop"
print "After the loop"
Yet other languages, such as Ada and many variants of BASIC, use additional reserved words as in the following example of branching
if condition then
-- statement 1
-- statement 2
-- ...
else
-- statement 1
-- statement 2
-- ...
end if
The “then” starts a new block which goes to the “else” which starts another block which ends at the “end if”. Many of these languages also have a generic “begin” and “end” to delineate blocks.
Finally, Lisp and related languages such as Scheme or Clojure use so-called s-expressions, which are lists where each list starts with a ( and ends with a ) and has zero or more elements in it. In these languages there are no simple statements. Instead everything has a value, even the rough equivalent of a block, which is “progn”. For instance (progn (+ 3 5) (* 2 7)) first adds 3 and 5 and then multiplies 2 by 7. The value of this “block” (really expression) is the last value, i.e. 14. I am planning a whole series of posts down the line on Lisp.
As it turns out, there can be more to blocks than just grouping statements. At least in some programming languages, such as C and C++, variables that are defined inside a block exist only while the code inside that block executes. For instance, the following C code
#include <stdio.h>
int main(void) {
int i = 3;
if (1) {
int i = 5;
printf("%d", i);
}
printf("%d", i);
return 0;
}
outputs first 5 and then 3. This is not the case for Javascript as you can see by trying the following:
var i = 3;
if (1) {
var i = 5;
print(i);
}
print(i);
If you run this you will find that both the first and the second print output a value of 5. The var i inside the block did not create a variable only inside of this block but changed the value of the variable i that was defined outside of the block. We will learn a lot more about this when we learn about variable scoping. Now we have the basics in place and next week can in fact learn about how to define new words in a programming language.
Posted: 17th July 2012 – Comments
Tags:
tech tuesday programming control structures
Tech Tuesday: Control Structures
Last time in the Tech Tuesday cycle on programming we saw that so-called reserved words have special meaning. They effectively constitute the built-in vocabulary of a programming language. Now let’s go all the way back to the basic analogy that I used for the overview post: programming is telling a computer what to do, which is very much like telling a person what to do.
One of the expressive abilities that is required for that are conditionals, as in: if the front door is locked, then go around the house to the back door. In other words, some of the instructions apply only if a certain condition is encountered. All programming languages have some notion of a conditional statement. For instance, in Javascript we can say
if (a < 0) alert (a + " is a negative number");
This alert will be executed only when the value of a is less than 0. The alert statement will be ignored otherwise. Now most languages also provide the ability to include alternative statements to be executed when the condition is not met as follows:
if (a < 0) alert (a + " is a negative number"); else alert (a + " is zero or a positive number");
Expressions such as “if” and “else” in a programming language that impact the flow of program execution are generally referred to as control structures.
Control structures come in two basic flavors: branching and looping. We already saw one example of branching with if and else. Many programming languages also have some kind of statement that lets us test many different cases and execute instructions accordingly. This usually goes by a name such as “case” or “select” or “switch” as in the following example from the programming language Pascal (copied from the Wikipedia entry on the switch statement):
case age of
0,1: writeln('baby');
2,3,4: writeln('toddler');
5..12: writeln('kid');
13..19: writeln('teenager');
20..25: writeln('young');
else writeln('old');
end;
As it turns out this is our first example of something called syntactic sugar. I am not sure where exactly that terminology comes from, but the idea is that “sugar” is something we use to make something taste better or be more palatable (cf Mary Poppins). The reason is that we could have used a series of if statements instead, as in the following (again in Pascal)
if (age = 0) or (age = 1) writeln('baby');
if (age = 2) or (age = 3) or (age = 4) writeln('toddler');
... and so on
Now if you look closely at the execution of the code in both cases you would notice that they might not be exactly equivalent. And that’s because in the second case every condition needs to be evaluated whereas in the first, depending on how case works the whole case statement could stop once one of the conditions has been met. As homework you might want to think about how to fix that problem.
Now the other type of control structure that we need is some kind of ability to repeat a set of instructions. Again this is something we do naturally when giving instructions to a person as in “keep turning the key until the door is unlocked.” The “turning of the key” is to be repeated until a condition is met, in this case that the door is unlocked. Unlocking could require one or more turns of the key. The Pascal programming language had a specific control structure which exactly mimics this:
repeat turn(key, door) until (is_unlocked(door))
Of course it could turn out that the door is already unlocked before you turn the key at all. In that case the above instructions will still turn the key at least once which might either be a wasted effort or in fact wind up locking the door by mistake. So what we want instead is a control structure that first tests a condition and only repeats the instructions if the condition applies. That turns out to be the more common loop structure in programming. Pretty much every programming language has a version of the while loop as in:
while (is_locked(door))turn(key, door)
And in those cases where you do want to test the condition after executing the loop at least once most of those language instead of using entirely different reserved words as in Pascal, allow you to say something like
do turn(key, door while(is_locked(door))
You will notice that this is not as intuitive for a human reader as the Pascal example that I gave above because the condition we are testing is the opposite of the end state we are trying to reach. We need to keep repeating as long as the door is still locked.
For loops too many programming languages provide a variety of syntactic sugar. The most common is the nearly ubiquitous for loop. Let’s say you wanted to display the numbers 1 through 5, here is a Javascript for loop that would accomplish that:
for(i = 1; i < 6; i++) alert("Counter is " + i);
var i = 1;
while (i < 6) {
alert("Counter is " + i);
i++;
}
The argument in favor of having a separate for loop is that it can be easier to read because it pulls the initial state (i = 1), the condition to be tested (i < 6) and the change to occur on each iteration (i++) all right next to each other. That can make it easier to understand what is going on in the loop. In general though it is worth being mindful of syntactic sugar as just with regular sugar having too much of it can be a bad thing. Some languages (Perl comes to mind) have a ton of it and reading someone else’s code can become quite tricky.
The key take away from today should be that programming languages come with a variety of control structures but all you really need is branching (if) and looping (while). Every possible control flow can be put together with just those two. And in an upcoming post we will encounter recursion as an alternative way to loop. But before we can do that we will need to learn about defining our own “words” as a way of extending a programming language, so that we can actually say something like turn(key, door) as in the example above.
Posted: 10th July 2012 – Comments
Tags:
tech tuesday programming control structures

