Home
Intro
LC
ACR
About

Day 4 - Control Flow in Pascal

-=-=-=-=-=-=-=-=-=-=-

What you are going to learn today:

  • What control flow is
  • The different types of control flow loops
  • And example programs to demonstrate

-=-=-=-=-=-=-=-=-=-=-

Control Flow is the control of how a program executes in Pascal. It is neccesary if you don't want the program code to run sequentially or when you need to run code only under certain conditions. This tutorial will teach you the different control flow loops.

So, what is control flow?

Well, just imagine that you're Bill Gates. You're overflowing with money, and you're planning to get a can of Coke from the Coke machine right outside your office. You step out, take a deep breath, and dig out your heavy wallet from your pocket. Ahh, there are two possibilities for what that will happen after this:
  1. Realising that your wallet only has notes in it, you groan and mutter something about "the advancement of mordern technology", then go off looking for the nearest human Coke vendor...
  2. Or, you take out all the coins you have and dump them one by one into the Coke machine, hoping that Coke isn't sold out. Yet.
Well, congratulations! You've just gone through your first course through control flow! When you were standing in front of the Coke machine, there were two possibilities, right? If you didn't have coins, you would have to go to a human vendor. Otherwise you would buy your Coke as normal. Well, that's control flow! Control flow is simply just controlling how the program flows, making decisions, looping code, and other things like that. Whenever you need to have the program do things that aren't sequential, you'll have to use control flow to modify the program sequence. Otherwise, it just can't be done. In Pascal, there are a few control flow loops for you to use. Most of them are pretty logical, so without further ado, let's go on to find out what they are.

The different control flow loops follow...

Here they are, in order of usefulness, the grand, the fantastic, the wonderful, and the unbelievably complex control flow loops! Here for your personal reading enjoyment!

1. The if-else statement

if food = yummy then say('That's good!') else say('Em, never mind.'); When you need to make decisions in code, the if-else statement fits the job perfectly. A typical if-else statement looks like this:
  if a = 30 then
    Writeln('A is equal to 30')
  else
    Writeln('A is not equal to 30');
An if-else statement is actually a conditional statment that will execute code only if a condition is true. If the 'else' keyword is there and the condition is not true, then the second line of code will be executed instead. The condition is stated between the keywords 'if' and 'then'. In this case, the condition is 'a = 30' which tests whether the value of a is equivalent to 30.
    Rem - The '=' is used for testing for equality, but the ':=' is for assigning values. Don't mix them up! Use the '=' for testing if two values are the same, but ':=' if you want to assign something a value.
if a is equivalent to 30 the first line code would execute, printing "A is equal to 30" on the screen. However if a is not equal to 30, it would execute the line immediately after 'else', printing "A is not equal to 30". Magic! Pure magic!
Now, you may ask two questions. One, how come the first line of code has no semicolon at the end? Simple. There's no semicolon as the entire if-else thing is one big statement! If the 'else' part is removed, then that line would require a semicolon. In contrast...
  if a = 30 then
    Writeln('A is equal to 30');
If a is equal to 30 then the program will print "A is equal to 30". Otherwise, it won't do anything.
The second question that might be in your mind would be how do you execute more than one line in the if-else statement? Logically, you would do this:
  if a = 30 then
    Writeln('Congrats!')
    Writeln('A is equal to 30')
  else
    Writeln('A is not equal to 30');
However, this is totally wrong! Whenever you need to type more than one line in a place where only one line is accepted, you need to use a new code block! Yes! You actually type another set of 'begin' and 'end'! Thus, what the above should look like is this:
  if a = 30 then
    begin
      Writeln('Congrats!');
      Writeln('A is equal to 30');
    end
  else
    Writeln('A is not equal to 30');
Notice that there's also no semicolon after the 'end'. Pascal treats the whole code block as one line of code! Well, confused? Ahh, there's nothing better than an example program to solidify everything...

Type

1: program TestTheNumber;
2:
3:   var
4:     a: integer;
5:
6:   begin
7:     a := 12;
8:
9:     { This tests if a is less than 50 }
10:    if a < 50 then
11:      Writeln('A is less than 50')
12:    else
13:      Writeln('A is more then 50');
14:  end.

Run

A is less than 50

Analyse

Dissection Time! This program is easier than you think! You may see some unfamiliar signs, but besides that, it's all logic...

  • Line 4 - We declare the variable a here.
  • Line 7 - Now, we assign the value 12 into a.
  • Line 10 - Here, we test if a is less than 50. That < sign means 'less than'. Other operational and relational operators will be introduced to you later. If a is less then 50 then the code on line 11 will execute, else the code on line 13 will execute.
  • Line 11 - This line executes only if a is less than 50
  • Line 13 - This line executes only if a is not less than 50

Ahh, you learnt something new today. The mathematical sign for less than works the same way in Pascal! You may be wondering, what other operators are there? Well, here they are:

Operator Operation
= Equal
<> Not equal
< Less than
> More than
<= Less or equal
>= More or equal

Also, you can have multiple tests in one condition by enclosing them in brackets and linking them with 'and', 'or', or 'xor'. For example:

  if (a > 50) and (a < 100) then
    Writeln('A is more than 50 and less than 100');
Only when the first condition and second conditions are met, will the message be printed out. Wondering what the other two operators do? Here's something called a truth table to help you:

andorxor
TrueTrueTrueTrueFalse
TrueFalseFalseTrueTrue
FalseTrueFalseTrueTrue
FalseFalseFalseFalseFalse

As you can see, 'and' only returns true if all conditions are true, 'or' returns true as long as one of them is true, and finally, 'xor' returns true only if one is true and the other false. Don't worry if you can't get it for now, it's really simple once you get the hang of it.

2. The for loop

When you need to repeat a certain bit of code again and again, the for loop is just what you need. It lets you specify the exact number of times the code is repeated, giving you the flexibility you always dreamed of. (Then again, who dreams about making code repeat as many times as you want?)
The for loop uses a counter which increases by one each time the code is repeated. That means that you need to declare a variable before you can use the for loop. The for loop looks like this:
  for i := 1 to 10 do
    Writeln('Help! I'm being multiplied!');
Ah, the beauty of it all. As you can see, after the word 'for', we place the name of the counter variable. Then, we ask it to loop from 1 to 10, successfully repeating the line of code 10 times. Also, every time a loop is finished, i increases by 1. And yes, you can actually use i in your code! Look at the example below:
  for i := 1 to 10 do
    x := x + i;
Assuming that x starts of with 0, the end result would be 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10, which equals 55. Of course there are other uses for this feature, but this exercise will left up to the reader.
    Tips - A quick way to calculate the above is to use the Gauss Theorem, which works because 10+1, 9+2, 8+3, 7+4, 6+5, all equal to 11. Thus, the sum above is actually equivalent to 5 times 11. Go figure that out for yourself...
Now you may ask, how do you make the counter go backwards? Well instead of typing 'to' type 'downto'. The counter will then count backwards. See?
  for i := 10 downto 1 do
  x := x + i;
Now that you know everything there is to know about the for loop, let us once again have another example program to round the for loop up. (After all, the fun part is in the typing, isn't it?)

Type

1: program LoopyLoop;
2:
3:   var
4:     i: integer;
5:
6:   begin
7:     for i := 1 to 5 do
8:       Writeln('This is loop number ', i, '.');
9:     for i := 5 downto 1 do
10:      Writeln('This is loop number ', i, '.');
11:  end.

Run

This is loop number 1.
This is loop number 2.
This is loop number 3.
This is loop number 4.
This is loop number 5.
This is loop number 5.
This is loop number 4.
This is loop number 3.
This is loop number 2.
This is loop number 1.

Analyse

For loops are demonstrated perfectly in this example program. Now, take out your tools, it's dissection time!

  • Line 4 - This declares the variable i
  • Line 7 - This loops i from 1 up to 5
  • Line 8 - This line prints out a message with the value of i
  • Line 9 - This loops i down from 5 to 1
  • Line 10 - This prints exactly the same thing as Line 8.

As you can see clearly above, the loop is repeated from 1 up to 5 and 5 back to 1 again. Well, that's nice, but what if you want a sort of mix between the two? You know, repeat something until a condition is satisfied, or while a condition is true... Well, what you're looking for is just up next! 'Repeat-until' and 'while' loops do just that, so read on!

3. Repeat-Until and While Loops

Repeat-Until loops repeat a sequence of code until a condition is satisfied. For example, you can say: repeat tearing up the documents until there are no more documents left. That can be directly translated to Pascal code.
  repeat
    x := x - 1;
  until x = 0;
This code will loop again and again until x is equal to 0. In other words, x would be decreased by 1 repetitively until it is 0. Yes, I can see that look on your face. You're thinking of ways to make use of this, aren't you? Clever boy!
    Rem - In case you're desperate for accuracy, you'd like to know that Pascal actually states that you are to leave out the semicolon on the last line of any code block. That also includes the repeat-until loop, because that code between 'repeat' and 'until' is also considered a code block! Placing a semicolon however, still works, because Pascal 'adds' an extra empty line without a semicolon at the end. And yes, it is recommended for you to place semicolons anyway. Better than griping around later adding strain onto your keyboard!
Now, about the while loop. The while loop is a very close cousin of the repeat-until loop and works in almost the same way. The loop will repeat itself only while the condition is true. Once the condition becomes false, the loop exits. Here's how it looks like:
  while x <> 0 do
    x := x - 1;
This is a variation of the repeat-until loop above, except that it checks if x is not 0. If that is true, it will decrease x by 1. However, once x reaches 0, the loop exits and continues with the rest of the code.
Here, some of you may ask, what's the difference between the two loops? Well, for the repeat-until loop, the code will be run at least once. In other words, no matter what the condition is, the code will be run first, then the condition tested. For the while loop however, the test is carried out first before deciding whether to execute the code. Thus, the code may not be run at all.
Well, below is an example program to demonstrate these two loops. Pay close attention to what happens, and try to figure out why.

Type

1: program LoopADoop2;
2:
3:   var
4:     x: integer;
5:
6:   begin
7:     x := 1;
8:     while x <= 5 do
9:       x := x + 1;
10:    Writeln(x);
11:
12:    x := 1;
13:    repeat
14:      x := x + 1;
15:    until x >= 5;
16:    Writeln(x);
17:  end.

Run

6
5

Analyse

Now, let's analyse this. What do you think makes the answers different? Well, let's figure out why. (Better than leaving you alone in the dark...)

  • Line 4 - Declares variable x
  • Line 7 - Assigns 1 to x
  • Line 8, 9 - Ah, here's our first loop. First, the loop tests if x is less than or equal to 5. If so the loop runs the code. So, if you trace the loop, you'll see that the loop repeats five times, with the final value of x being 6. Ta-da!
  • Line 10 - This prints out the value of x
  • Line 12 - Resets x
  • Line 13, 14, 15 - Now, you may have noticed that the difference between this loop and the while loop is that while the while loop (pun intended!) provides a condition to continue the loop, the repeat loop gives a condition to end the loop. Thus, if you trace the loop again, once x reaches 5, the loop stops instead of continuing one more time like the while loop! Amazing!

So, now you know these two very simple loops, it's finally time to mention our last and final control flow loop - the case statement. Pretty complicated, but very useful in future!

4. The case statement

The case statement is very similar to multiple if statements. In fact, it was created to replace messy code caused by to many ifs! The case statement takes a value, looks it up against a list, and if it finds an equivalent value, it will run the code associated with it. If the value is not found, it runs the default code, if there is any. Confusing? Em, it'll be better if you get a look at how the case statement looks first:

  case x of
    1: Writeln('X is equal to 1');
    2: begin
         Writeln('Did you know?');
         Writeln('X is equal to 2');
       end;
  else
    Writeln('X is not equal to 1 or 2!');
  end;
As you can see, the case statement looks at x, checks it against 1, then 2, and if x is not equal to any of those, it prints "X is not equal to 1 or 2!". Fantastic! Note that you can leave out the else part in a case statement. Without it, when no match is found, the case statement will do nothing. Ahh, easy does it.
Some of you may be wondering though, what if there are two values x can be equal to? Which one will it run? For example:
  case x of
    1: Writeln('X is equal to 1');
    1: Writeln('1 is equal to x');
  end;
Well, the case statement will print the first line but not the second. The case statement only executes code attached to the first matching value. The rest are history. However, that's not the only thing you need to remember about the case statement. Here's are some case pointers:
  1. The values you input for case to match must be constants. You cannot ask, for example, for case to match x with another variable like y. However, it can work with a numeric constant you had declared or an explicit numeric number.
  2. You can only use case with numbers or characters, nothing else. That means no strings are allowed! (Wait a minute, I haven't even used a string yet!)
  3. You can attach code to more than one value in a case statement. For example, if you want a certain piece of code to execute when the variable matches 1 to 50, you can type '1..50'. That's a 1, two full stops, and a 50. You can also specify different values at one go by seperating them with commas. Example: '1, 5, 8' will match a variable if it is either 1, 5, or 8.
  4. No, case has nothing to do with Long John Silver's treasure chest.
I bet you're swirling with questions right now, so here's your final example program! Good luck! Here we go...

Type

1: program TheMysteryCase;
2:
3:   var
4:     x: integer;
5:
6:   begin
7:     x := 5;
8:     case x of
9:       1..50: Writeln('X is between 1 to 50');
10:      51..100: Writeln('X is between 51 and 100');
11:    else
12:      Writeln('X is off the range of 1 to 100!');
13:    end;
14:  end.

Run

X is between 1 and 50

Analyse

This is fantastic! Here the case statement is used to check whether x is between 1 and 50 or 51 and 100. This is how it works:

  • Line 4 - Declares variable x
  • Line 7 - Assigns 5 to x
  • Line 8 - This line starts the case statement to test x
  • Line 9 - If x is between 1 and 50, it will print the appropiate message
  • Line 10 - If x is between 51 and 100, it will print the appropiate message
  • Line 12 - If x does not fit both coditions, it will print this message
  • Line 13 - This ends the case statement

Simple, easy, sweet. That's how the case statement works. You might have noticed that this program could have been written simply using one if statement, but hey, this is just an example!

The End Of It All

This marks the end of Day 4. Next up, is Day 5, Procedures and Functions. Ahh, that was a long one. Loosen up, you're going to learn something new!

-=-=-=-=-=-=-=-=-=-=-

HomeIntroLCACRAbout
Back to Class B

-=-=-=-=-=-=-=-=-=-=-

This page is ThinkQuest entry 11127.
email: tq97-11127@advanced.org