WHAT CONTROL STATEMENTS DO

In Lesson 1, you learned that a program is just a set of instructions that tell a computer what to do in a language it can understand. In this lesson, you'll learn about the different logical structures in a computer program that you use to create those instructions.

Every scripting or programming language has a different set of rules -- called its syntax -- for using these different structures in a program written in that language. Although the syntax may be different across languages, the basic use of each structure is the same. For a general discussion, we like to avoid using only the syntax of a single language, so we use pseudocode . Pseudocode is simply a way of writing instructions in something close to natural English but that's related to typical programming languages. Don't worry, it will all become clear.

Scripting languages and full programming languages use structures called control statements to hold instructions that help computers make decisions about what to do ( conditional statements ), or perform tasks multiple times ( loops ).

For example, say you want to have the computer read your e-mail for you and then delete all the messages you've received that look like spam advertisements. In this case, you'd want the program to do the following:

  • Open your e-mail inbox and find your new e-mail messages.
  • Look at the first message.
  • See if this message looks like annoying spam.
  • Delete the message if it looks like annoying spam.
  • Leave the message untouched if it may be a real message.
  • Go on to the next message and repeat the process until all messages have been checked.

In this case, you're having the computer do work for you. To do that, it has to be able to make decisions. You have to tell it exactly what to decide, and when. This is one of the fundamental rules of programming: Computers only do what their instructions tell them.

In the case of this e-mail routine, the computer has to make a decision with each message whether or not it should delete it. You have to tell it to check the e-mail subject, and then what text to look for. What the computer does from there depends on the message passing this subject-matching test. This example includes both a conditional statement (if the message subject has certain words, delete the message) and a loop (keep checking each message until all messages are tested).