Computer Science: the for loop

Tutoring math – especially if you have a degree in it – you likely realize that some of your students are on their way to computer science courses.  The math tutor opens the discussion on programming with the concept of the for loop.

Although computer programming offers separation from the machine that was unknown twenty years ago, the basic constructs of how a computer processes data are more relevant than ever.  After all, more and more people are, undoubtedly, headed towards the field.

A loop is a repeating operation that continues until some external condition is met.  Alternatively, the loop may be infinite.

The for loop is the type of loop that is often learned first in computer programming.  Its basic structure:

for

the number of times a counter variable remains less than the upper limit

perform

these instructions
increase the counter

back to for

Giving a real example of a for loop, the immediate question is which language to use. Imagine a space traveller arrived on earth and asked how to say “Hello”. You’d tell them “Hello” in your own language; there isn’t a universal way to say it.

Computer science offers the added complication that preferred languages change. Someone “in the know” might well ask, Why did you show it in that language?

The language I’m introducing the for loop in is perl. Known as “the duct tape of the internet,” it was critical in the early web boom. Now it has competition from some languages purported to be easier to use. Perl is famously powerful and well-loved by its own programmers. It was developed by Larry Wall in 1987. The name is an acronym: Practical Extraction and Reporting Language.

Here is a perl for loop:

for(\$i=0;\$i<3;\$i++){

print “The counter is now at $i.\n”;

}

The above loop outputs the following:

The counter is now at 0.
The counter is now at 1.
The counter is now at 2.

For a detailed explanation of how the code above produces that output, please return soon. I’ll also discuss how to start experimenting with perl yourself, should you catch the bug:)

Jack of Oracle Tutoring by Jack and Diane, Campbell River, BC.

Tagged with: ,

Leave a Reply