beanz Magazine

Control Flow

Ryan Mitchell on Flickr

How do programming languages control the flow or processing of instructions? Here's how control flows work in several languages.

Before we begin, these Code Snippets articles demonstrate how a single task or concept is handled in different programming languages. The goal is to help you feel more comfortable reading unfamiliar code, as well as explore differences between languages. The word red in English sounds and looks similar to rouge in French and rojo in Spanish. Programming languages often have similarities that provide insights into each language.

You might think a wide flooded river flows anywhere it wants. However, the landscape of dirt and rocks water passes over defines how fast and where the river flows. Programming languages work in a similar way. Programmers create a set of instructions to follow after a person does things with the software application. Typing your name in a website form then clicking a button to submit the data, for example, causes the website code to process the data from the submitted form.

How do programming languages control the flow or processing of these instructions? The answers are really interesting.

Probably you know about the if/elseif/else construction in programming. You write code that provides a series of conditions with instructions what to do when those conditions are met. For example, if a website form is submitted with no data, the first condition might be to check for no data returned from the form. If a person submits a form with no data, then the website displays an error message. Otherwise (else), the website processes the data from the form.

This is simple stuff. Far more interesting are the concepts of loops, early exit, redo, and retry which are part of control flows.

Loops do a set of instructions as long as a condition exists. If you want to display the four most recent news items, you would do the instructions to display the latest news item only four times then exit. Or let’s say your instructions need a piece of critical information to do all the instructions. If the critical information is not available, you might exit the loop early.

A number of programming languages also use a flexible control structure to replace the more rigid if/elseif/else structure. In C and Swift, as we’ll see below, it’s called a switch statement, with a case replacing an if statement, and it’s used to match as many cases as you want, with each case triggering code instructions. It’s a visually more clean way to organize the flow of instructions.

To control programming instructions, code is organized into blocks. Whether or not the code instructions inside a block are used depends on whether or not the conditions for the block are met, usually with the if/elseif/else control flow structure. If a person submits a form with no data, for example, then a block of code returns an error message.

These and other concepts make up control flows in programming languages. Here are how different programming languages actually use control flows.

C

The most common control flow determines if something is true or false, also called boolean. In C, there is no boolean type. If you want to know whether or not something is false, you use 0. If you want to know if something is true, you use not equal to 0 or non-zero. Here’s a basic control structure in C:

int hedgehogs = 10;
if (hedgehogs != 0) {
    //do something
}

In this example, hedgehogs is defined as an integer (int, or number) equal to 10. The control flow statement evaluates if the number of hedgehogs is not equal (!=) to 0, which the C language defines as false. In real life, the number of hedgehogs would be set elsewhere in the code, possibly when a person completed a form where they entered the number of hedgehogs they had said hello to that day. The //do something bit in the code block above is a comment that is not visible when C code is run.

Here’s how the C language handles multiple if statements with a switch, like a pinball machine where the ball slips down through a series of paddles and bumpers, except programming uses a set of code instructions:

int hedgehogs = 10;
switch (hedgehogs) {
case 1:
    //do something
    break;
case 2:
    //do something
    break;
case 3:
case 4:
    //do something
    break;
default:
    //do something
    break;
}

From the first code example, you know the hedgehogs variable is defined as an integer (number) and set to 10. This code uses the value of hedgehogs (which is 10) to determine what code instructions to do. Because we have 10 hedgehogs, can you tell which instructions are used? It’s the default case, isn’t it? It’s the only case that could include a value of 10. With a switch control structure, default works similar to the else part of an if/else control structure. The break; bit of code exits the switch.

Also notice, in this switch example, how instructions for 3 hedgehogs is the same as 4 hedgehogs. You can stack multiple conditions to save space and make your code more visually understandable.

Code instructions also can be set to loop while or until a condition is met. These are called while and for control structures. Here’s how they work in the C language:

int hedgehogs = 10;
while (hedgehogs <= 10) {     //do something }

This code will loop while the value of hedgehogs is less than or equal to (<=) 10. The //do something part has any instructions, often increasing or decreasing the value of a variable like hedgehogs until the while condition is met or exceeded.

Loops also can do things as part of a for control structure. It works similar to a while statement but the conditions are grouped into a single tight package, usually in this form in the C language:

for (initialization; test; increment) {
    //do something
}

where initialization is the initial value or assignment of a value to a variable, test is the condition to test for during the loop, and increment indicates whether to add or subtract from the initial value until the for condition is met or exceeded. Here's an example in C:

for (i = 5; i > 0; i--) {
    printf("%d ",i);
}

In this example, the variable i is set equal to 5, the test is the variable i must be greater than (>) 0, and we will subtract 1 (--) from the variable i each time this for loop is run, until the variable i is no longer greater than 0. The instruction printf("%d ", i) prints out each number until the variable i is no longer greater than 0. The "%d " bit prints the current value of the i variable with a space between it and any numbers printed next.

Can you tell what this for control flow structure prints out? It prints out 5 4 3 2 1.

Now let's make this a little less scary and reverse this for loop code:

for (i = 1; i <= 5; i++) {     printf("%d ",i); }

I bet you can tell what this prints out: 1 2 3 4 5. Do you see the differences in the for statement here and in the example above? Here we set the i variable to 1, then run the for statement until the variable is tested as less than or equal to (<=) 5, and each time we repeat the for loop we add 1 (++) to the value of the i variable.

We've spent a lot of time with the C language because it has influenced many other programming languages. Let's quickly look at control structures in one or two other languages to find differences.

Python

Here's an if/elseif/else control flow structure in Python, from their documentation:

if x < 0:     //do something elif x == 0:     //do something else:     //do something

There are a few wonderful differences here between Python and C. Notice how elseif becomes elif. And how the curly braces in C are replaced with a single colon after the condition is stated. As it happens, this if/elif control structure in Python is used instead of the switch structure in C and other languages.

And here's a for structure written in Python:

words = ['squirrel', 'tree', 'climb'] for w in words:
    print w, len(w)

This prints this output:

squirrel 8
tree 3
climb 5

In this example of a for structure in Python, first we create a list of words then we run a simple for statement to run through our list of words. For each word in our list, we print out the word (w) and next to it the length (len or number of characters, in this case) of each word. The only odd part is the w in the for w in words statement. In this case, w is a variable we create to make it easy to assign a word in our list to a variable each time the for statement is run. If we had 50 words, this for statement would run 50 times. In this case, we have 3 words so the for statement is run only 3 times.

Of course, Python has many more ways to control the use of code instructions.

Swift

Let's look at Apple's new programming language, Swift, to see how they do conditionals and control flow structures. Most people are not familiar with the language and, as a result, Swift has interesting solutions to the problem of controlling code instructions.

Here's a simple if/elseif/else control structure in Swift:

var temperatureInFahrenheit = 30
if temperatureInFahrenheit <= 32 {     println("It's very cold. Consider wearing a scarf.") } else if temperatureInFahrenheit >= 86 {
    println("It's really warm. Don't forget to wear sunscreen.")
} else {
    println("It's not that cold. Wear a t-shirt.")
}

There are a couple neat things here, given the C and Python examples. Swift uses curly braces, like C, but doesn't wrap statements (the temperatureInFahrenheit <= 32 bit) in braces, like Python. As in the C language, in Swift variables are set with a prefix (var). However, var doesn't specify the type for the variable. In this case, the temperatureInFahrenheit variable is set to an integer type with a value of 30. With C, if you recall, we set the variable for the number of hedgehogs as int for an integer or number, like this:

int hedgehogs = 10;

Even more interesting are the differences between Swift and C with switch control structures. Here is a switch written in Swift:

let someCharacter: Character = "e"
switch someCharacter {
case "a", "e", "i", "o", "u":
    println("\(someCharacter) is a vowel")
case "b", "c", "d", "f", "g", "h", "j", "k", "l", "m",
"n", "p", "q", "r", "s", "t", "v", "w", "x", "y", "z":
    println("\(someCharacter) is a consonant")
default:
    println("\(someCharacter) is not a vowel or a consonant")
}

This switch structure prints out e is a vowel. The first neat part is the let statement. In Swift, we let the variable someCharacter equal the character e, a vowel. Then we use the switch structure to evaluate the variable someCharacter to see if we can find a match for its value (e).

Remember how the C programming language let you stack case statements? Here's a switch structure in C, from earlier:

int hedgehogs = 10;
switch (hedgehogs) {
case 1:
    //do something
    break;
case 2:
    //do something
    break;
case 3:
case 4:
    //do something
    break;
default:
    //do something
    break;
}

In Swift, you can't combine or stack case 3 and case 4. Stacking case statements one on top of the other generates an error message. Instead, you put all the conditions in a comma-separated list. When a match is made, then code instructions are executed. Also notice how the Swift code has no break instructions at the end of each case statement? In Swift, the break statement is optional. It's implied.

 

While this article is long, hopefully you can see how a simple problem — how to control the use of code instructions — is solved by a few programming languages, in ways both similar and different.

Learn More

Control Flow/Loop

http://en.wikipedia.org/wiki/Conditional_loop
http://en.wikipedia.org/wiki/Control_flow

C

http://en.wikibooks.org/wiki/C_Programming/Control
http://www.cprogramming.com/tutorial/c/lesson3.html

Python

https://docs.python.org/2/tutorial/controlflow.html
http://www.openbookproject.net/books/bpp4awd/ch04.html
http://stackoverflow.com/questions/60208/replacements-for-switch-statement-in-python
http://codingstyleguide.com/style/180/python-pythonic-way-to-implement-switchcase-statements

Swift

https://developer.apple.com/library/ios/documentation/swift/conceptual/Swift_Programming_Language/ControlFlow.html

Also In The November 2014 Issue

Find Summer Tech Camps

It's that time of year: time to start thinking of summer tech camps for 2015. Here are a few ideas where to begin looking.

Rachel Manning Talks Software Development and the Freelance Life

Rachel Manning talks about her life as a freelance software developer building websites and web applications from her home in Mammoth Lakes, California.

Holiday Toy Ideas

Here are lots of ideas for computer science and programming toys kids might like, based on different age groups.

Create a Website with Wix

Wix.com is a free online tool you can use to create a website. Here's a basic tutorial to get started, as well as files to build a test site.

Chris Bradfield Talks Coding, Games, and Helping Kids Code

Chris talks about his journey from TRS-80 computers to websites to the game business to teaching kids to code in summer camp.

Control Flow

How do programming languages control the flow or processing of instructions? Here's how control flows work in several languages.

Destinations and Systems

Designers of products, content, and software use the concepts of destinations and systems to create content and apps for all our devices.

If builders built buildings the way programmers wrote programs, then the first woodpecker that came along would destroy civilization.

November 2014 Learn More Links

Links from the bottom of all the November 2014 articles, collected in one place for you to print, share, or bookmark.

November 2014 News Wire

Interesting stories about computer science, software programming, and technology for October 2014.

FTP

FTP is a mysterious yet extremely useful way to send data across computer networks. Here's a short overview with links.

Coding Books for Kids

No Starch Press sent along four books for kids. If you don't have them already, look them up at the library or buy online or in a bookstore.