LOOPS & CONTROL STRUCTURES
Every program we have examined to this point has been a simple one pass through with no statements being repeated. As in all other languages, Pascal has extensive capabilities to do looping and conditional branching. We will study these in this chapter.
THE FOR LOOP
Example program ------> LOOPDEMO.PAS
We will start with what may be the easiest structure to understand, the for loop. This is used to repeat a single Pascal statement any number of times we desire. Load LOOPDEMO.PAS and we will discuss the loops presented there.
The example illustrated in lines 13 and 14, is the simplest loop and does nothing more than execute a Writeln 7 times. We have three new reserved words, for, to, and do which are used as shown. Any simple variable of type integer, byte, or char can be used for the loop index but due to the requirement that everything must be defined prior to use in Pascal, the loop index must be defined in a var statement. Following the reserved word do is any single Pascal statement that will be repeated the specified number of times. Note that the loop is an incrementing loop but substitution of downto for to will make it a decrementing loop as is illustrated in the last example in this program. It should be pointed out that the loop control variable can only be incremented or decremented by 1 each time through the loop in Pascal.
A COMPOUND PASCAL STATEMENT
The example given in lines 18 through 22 contains our first compound Pascal statement. It was mentioned in Chapter 1 that the begin end pair of reserved words could be used to mark the limits of a compound statement. In this case, the single compound statement, starting with the begin at the end of line 18, and extending through and including the end statement in line 22 is the single Pascal statement that will be executed 10 times. A second variable Total has been introduced to simply add another operation to the loop. Any valid Pascal operation can be performed within the begin end pair, including another for loop, resulting in nested loops to whatever depth you desire.
The third example shows how the char type variable could be used in a for loop. Pascal requires that the loop index, the starting point, and the ending point all be of the same type or it will generate an error message during compilation. In addition, they must be variables of type integer, byte, or char. The starting point and ending point can be constants or expressions of arbitrary complexity.
The fourth example is a decrementing loop as mentioned earlier. It uses the reserved word downto, and should be self explanatory.
THE IF STATEMENT
Example program ------> IFDEMO.PAS
Pascal has two conditional branching capabilities, the if and the case statements. We will look at the simplest of the two now, the if statement. Load IFDEMO.PAS for an onscreen look at the if then pair of reserved words first illustrated in lines 11 and 12. Any condition that can be reduced to a boolean answer is put between the if then pair of words. If the resulting expression resolves to TRUE, then the single Pascal statement following the reserved word then is executed, and if it resolves to FALSE, then the single statement is skipped over. Of course, you can probably guess that the single statement can be replaced with a compound statement bracketed with a begin end pair and you are correct. Study example 1 and you will see that the line will always be printed in this particular fragment because Three is equal to One + Two. It is very difficult to come up with a good example without combining some of the other control structures but we will do so in the next example program.
The second example in lines 14 through 19, is similar to the first but has the single statement replaced with a compound statement bracketed by the begin end pair of reserved words and should be simple for you to understand.
The third example in lines 21 through 24, contains a new reserved word, else. As before, if the condition is true, line 22 will be executed. When the if condition is FALSE, then the single Pascal statement following else is executed. One and only one of the two statements will be executed every time this if statement is encountered in the program. Examination of the third example should clear this up in your mind.
Notice that the Pascal compiler is looking for either a semicolon to end the if, or the reserved word else to continue the logic. It is therefore not legal to use a semicolon immediately preceding the reserved word else. You will get a compiler error if you include the semicolon. This is a common error, but easy to fix, and you will quickly get used to writing it correctly.
THE IF-THEN-ELSE BLOCK
Put on your thinking cap because the next principle is difficult to grasp at first but will suddenly clear up and be one of the most useful facts of Pascal programming. Since the entire if then else block of code is itself a single Pascal statement by definition, it can be used anywhere that an executable statement is legal without begin end separators. This is shown in the fourth example of the IFDEMO.PAS Pascal example program. Lines 27 through 30 comprise a single Pascal statement, and lines 32 through 35 comprise another. The if statement begun in line 26 therefore has a single statement in each of its branches, and it is a single Pascal statement itself beginning in line 26 and ending in line 35. Reread this paragraph until you understand it completely, because it is a very important concept.
The if then else construct is one of the most used, most useful, and therefore most important aspects of Pascal. For this reason you should become very familiar with it.
Try changing some of the conditions in the example program to see if you can get it to print when you expect it to for your own practice. When you are ready, we will go on to a program with loops and conditional statements combined and working together.
LOOPS AND IFS TOGETHER
Example program ----> LOOPIF.PAS
Load LOOPIF.PAS and study it for a few minutes. It contains most of what you have studied so far and should be understandable to you at this point. It contains a loop (lines 7 through 17) with two if statements within it (lines 8 & 9 and lines 10 through 16), and another loop (lines 11 through 15) within the second if statement.
You should make careful note of the formatting used here. The begin is at the end of the line which starts the control and the end is lined up under the control word such that it is very clear which control word it is associated with. All statements within each control structure are indented three spaces which greatly adds to the readability. You will develop your own clear method of formatting your code in time but until then, it is suggested that you follow this example which is written in a manner which is acceptable within the general Pascal programming community.
An easily made error should be pointed out at this time. If an extraneous semicolon were put at the end of the if statement in line 8, the code following the statement would always be executed because the null statement (the nothing statement between the then and the semicolon) would be the conditional statement. The compiler would not generate an error and you would get no warning. Add a semicolon at the end of line 8 to see the error. Of course, you will need to compile and execute the program to see line 9 print for all 10 values of Count.
FINALLY, A MEANINGFUL PROGRAM
Example program ------> TEMPCONV.PAS
Load TEMPCONV.PAS and study its structure. Notice the header block that defines the program and gives a very brief explanation of what the program does. This program should pose no problem to you in understanding what it does since it is so clearly documented. If you study the style of indenting used here, you will learn to appreciate the clarity afforded by the indentation. Compile and run this program and you will have a list of Centigrade to Fahrenheit temperature conversions with a few added notes.
Example program ------> DUMBCONV.PAS
Load, examine, and run DUMBCONV.PAS for a good example of poor variable naming. The structure of the program is identical to the last program and when you run it, you will see that it is identical in output, but compared to the last program, it is difficult to understand what it does by studying the listing. We studied UGLYFORM.PAS in chapter 2 of this tutorial and it illustrated really stupid formatting that nobody would ever use. The poor choice of variable names and lack of comments in the present program is nearly as unreadable, but many programmers are content to write code similar to this example. You should be conscious of good formatting style and naming conventions from the start and your programs will be clear, easy to understand, and will run efficiently. This program, like the last should be easily understood by you, so we will go on to our next Pascal control structure.
THE REPEAT UNTIL LOOP
The next two Pascal constructs are very similar because they are both indefinite loops (indefinite because they are not executed a fixed number of times). One of the loops is evaluated at the top and the other at the bottom. It will probably be easier to start with the repeat until construct which is the loop that is evaluated at the bottom.
Example program ------> REPEATLP.PAS
Examine the file named REPEATLP.PAS to see an example of a repeat loop. Two more reserved words are defined here, namely repeat and until. This rather simple construct simply repeats all statements between the two reserved words until the boolean expression following the until is found to be TRUE. This is the only expression in Pascal that operates on a range of statements rather than a single statement and begin end delimiters are not required.
A word of caution is in order here. Since the loop is executed until some condition becomes TRUE, it is possible that the condition will never be TRUE and the loop will never terminate. It is up to you, the programmer, to insure that the loop will eventually terminate. Compile and execute REPEATLP.PAS to observe the output.
THE WHILE LOOP
Example program ------> WHILELP.PAS
The file WHILELP.PAS contains an example of another new construct, the while loop. This uses the while do reserved words and will execute one Pascal statement (or one compound statement bounded with begin and end) continuously until the boolean expression between the two words becomes FALSE. This loop is also indeterminate and could, like the repeat until loop, never terminate. You should therefore exercise care in using it.
There are two basic differences in the last two loops. The repeat until loop is evaluated at the bottom of the loop and must therefore always go through the loop at least one time. The while loop is evaluated at the top and may not go through even once. This gives you flexibility when choosing the loop to do the job at hand. Compile, run, and examine the output from the example program WHILELP.PAS.
THE CASE STATEMENT
The final control structure introduces one more reserved word, case. The case construct actually should be included with the if statement since it is a conditional execution statement, but we saved it for last because it is rather unusual and will probably be used less than the others we have discussed in this chapter.
Example program ------> CASEDEMO.PAS
The case statement is used to select one of many possible simple Pascal statements to execute based on the value of a simple variable. Load the file CASEDEMO.PAS and observe the program for an example of a case statement. The variable between the case and of reserved words in line 9 is the variable used to make the selection and is called the case selector. Following that, the various selections are listed as a possible value or range, followed by a colon, a single Pascal statement, and a semicolon for each selector. Following the list of selections, an else can be added to cover the possibility that none of the selections were executed. Finally, an end statement is used to terminate the case construct. Note that this is one of the few places in Pascal that an end is used without a corresponding begin.
The example file uses Count for the case selector, prints the numbers one through five in text form, and declares that numbers outside this range are not in the allowable list. The program should be self explanatory beyond that point. Be sure to compile and run this example program.
Example program ------> BIGCASE.PAS
Load and display the sample program BIGCASE.PAS for another example of a case statement with a few more added features. This program uses the identical structure as the previous program but in line 11 a range is used as the selector so that if the value of Count is 7, 8, or 9 this selection will be made. In line 12, three different listed values will cause selection of this part of the code. Of greater importance are the compound statements used in some of the selections. If the variable Count has the value of 2, 4, or 6, a compound statement will be executed and if the value is 3, a for loop is executed. If the value is 1, an if statement is executed which will cause a compound statement to be executed. In this case the if statement will always be executed because TRUE will always be true, but any Boolean expression could be used in the expression. This program uses silly data and constructs which do very little except to illustrate to you what can be done with these constructs. Be sure to compile and run this program, then study the output until you understand the result thoroughly.
This brings us to the end of chapter 4 and you now have enough information to write essentially any program desired in Pascal. You would find however, that you would have a few difficulties if you attempted to try to write a very big program without the topics coming up in the next few chapters. The additional topics will greatly add to the flexibility of Pascal and will greatly ease programming with it.
Advance to Chapter 5
Return to the Table of Contents