Programming Control Structures: by Dr. Wayne Brown
Programming Control Structures: by Dr. Wayne Brown
Introduction
One of the most important aspects of programming is controlling which statement will execute
next. Control structures / Control statements enable
a programmer to determine the order in which
program statements are executed. These control
structures allow you to do two things: 1) skip some Basic
statements while executing others, and 2) repeat one Commands
or more statements while some condition is true.
When you are solving a problem as a programmer, you must determine what
statements are needed to create a solution to the problem and the order in which
those statements must be executed. Writing the correct statements is one task. Statement 2
Sequential control is the "default" control in the sense that every statement
automatically points to the next statement in the flowchart diagram. You do not
need to do any extra work to make sequential control happen. However, using
sequential control alone will not allow the development of solutions for most real-world
problems. Most real world problems include "conditions" that determine what should be done
next. For example, "If it is after taps, then turn your lights out," requires a decision to be made
based on the time of day. The "condition" (i.e., the current time of day) determines whether the
action should be executed or not executed. This is called "selection control" and is introduced
next.
1 of 15
Selection Control
It is common that you will need to make a decision about some
condition of your program's data to determine whether certain
statements should be executed. For example, if you were calculating the
slope of a line using the assignment statement, slope ← dy / dx, then you need to make
sure that the value of dx is not zero (because division by zero is mathematically undefined and
will produce a run-time error). Therefore, the decision you would need to make is, "Is dx zero?"
A selection-control statement allows you to make "decisions" in your code about the current
state of your program's data and then to take one of two alternative paths to a "next" statement.
The RAPTOR code on the right illustrates a selection-
control statement, which is always drawn as a diamond.
All decisions are stated as "yes/no" questions. When a
program is executed, if the answer to a decision is "yes"
(or true), then the left branch of control is taken. If the
answer is "no" (or false), then the right branch of control Statement 1
is taken. In the example to the right, either statement 2a
or statement 2b will be executed, but never both. Note
that there are two possible executions of this example Decision
program:
Possibility 1 Possibility 2
Statement 1 Statement 1
Statement 2a Statement 2b Statement 2a Statement 2b
Statement 3 Statement 3
Decision Expressions
A selection-control statement requires an expression that can be evaluated into a "Yes/No" (or
True/False) value. A decision expression is a combination of values (either constants or
variables) and operators. Please carefully study the following rules for constructing valid
decision expressions.
As you hopefully recall from our discussion of assignment statement expressions, a computer
can only perform one operation at a time. When a decision expression is evaluated, the
operations of the expression are not evaluated from left to right in the order that you typed them.
Rather, the operations are performed based on a predefined "order of precedence." The order that
operations are performed can make a radical difference in the final "Yes/No" value that is
computed. You can always explicitly control the order in which operations are performed by
2 of 15
grouping values and operators in parenthesis. Since decision expressions can contain calculations
similar to those found in assignment statements, the following "order of precedence" must
include assignment statement expression operators. The "order of precedence" for evaluating
decision expression is:
1. compute all functions, then
2. compute anything in parentheses, then
3. compute exponentiation (^,**) i.e., raise one number to a power, then
4. compute multiplications and divisions, left to right, then
5. compute additions and subtractions, left to right, then
6. evaluate relational operators (= != /= < <= > >=), left to right,
7. evaluate any not logical operators, left to right,
8. evaluate any and logical operators, left to right,
9. evaluate any xor logical operators, left to right, then finally
10. evaluate any or logical operators, left to right.
In the above list, the relational and logical operators are new. These new operators are explained
in the following table.
The relational operators, (= != /= < <= > >=), must always compare two values of the
same data type (either numbers, text, or "yes/no" values). For example, 3 = 4 or "Wayne" =
"Sam" are valid comparisons, but 3 = "Mike" is invalid.
The logical operators, (and , or, xor), must always combine two Boolean values (true/false)
into a single Boolean value. The logical operator, not, must always convert a single Boolean
value into its opposite truth value. Several valid and invalid examples of decision expressions are
shown below:
3 of 15
Example Valid or Invalid?
(3<4) and (10<20) Valid
(flaps_angle < 30) and Valid, assuming flaps_angle and air_speed
(air_speed < 120) both contain numerical data.
5 and (10<20) Invalid - the left side of the "and" is a number, not
a true/false value.
5 <= x <= 7 Invalid - because the 5 <= x is evaluated into a
true/false value and then the evaluation of
true/false <= 7 is an invalid relational
comparison.
Start
Selection Control Examples
To help clarify selection-control "Enter your PGA"GET GPA
statements, please study the
following examples. In the first
example to the right, if a student
GPA >= 3.0
has made the Dean's List, then a Yes No
End
GPA >= 3.0
In the next example, one line of Yes No
text is always displayed, with the
value of the PGA variable
determining which one. Start
PUT "Congratulations for making the Dean's list!"¶
PUT "Sorry, you did not make the Dean's list."¶
End
GPA >= 3.0
In the next example, if the student Yes No
4 of 15 End
"Enter your PGA"GET GPA
A single selection-control statement can make a choice between one or two choices. If you need
to make a decision that involves more than two choices, you need to have multiple selection
control statements. For example, if you are assigning a letter grade (A, B, C, D, or F) based on a
numeric score, you need to select between five choices, as shown below. This is sometimes
referred to asStart
"cascading selection control," as in water cascading over a series of water falls.
Score >= 90
Yes No
Score >= 80
PUT "A"¶ Yes No
Score >= 70
PUT "B"¶ Yes No
Score >= 60
PUT "C"¶ Yes No
End
5 of 15
Loop (Iteration) Control
A Loop (iteration) control statement allows you to repeat one or more
statements until some condition becomes true. This type of control
statement is what makes computers so valuable. A computer can
repeatedly execute the same instructions over-and-over again without
getting bored with the repetition.
6 of 15
Statement3
Decision
Possibility 1 Possibility 2 Possibility 3 Possibility 4
Statement 1 Statement 1 Statement 1 (do you see the
Statement 2 Statement 2 Statement 2 pattern?)
Decision ("yes") Decision ("no") Decision ("no")
Statement 4 Statement 3 Statement 3
Statement 2 Statement 2
Decision ("yes") Decision ("no")
Statement 4 Statement 3
Statement 2
Decision ("yes")
Statement 4
In the RAPTOR example above, "Statement2" could be removed, which means that the first
statement in the loop would be the "Decision" statement. Or "Statement2" could be a block of
multiple statements. In either case the loop executes in the same way. Similarly, "Statement3"
could be deleted or be replaced by multiple statements. In addition, any of the statements above
or below the "Decision" statement could be another loop statement! If a loop statement occurs
inside a loop, we called these "nested loops."
It is possible that the "Decision" statement never evaluates to "yes." In such a case you have an
"infinite loop" that will never stop repeating. (If this ever happens, you will have to manually
stop your program by selecting the "stop" icon in the tool bar.) You should never write
statements that create an infinite loop. Therefore, one (or more) of the statements in the loop
must change one or more of the variables in the "Decision" statement such that it will eventually
evaluate to "yes."
A common mistake made by beginning programmers is to validate user input using a selection
statement. This can fail to detect bad input data because the user might enter an invalid input on
the second attempt. Therefore, you must use a loop to validate user input.
The two example RAPTOR programs below validate user input. Hopefully you see a pattern.
Almost every validation loop that you write will include an input prompt, a decision, and an
output error message.
7 of 15
Start
Loop
No
End
Counting Loops
Another common use of a loop is to execute a block of code a
specific number of times. This type of loop is called a counter-
controlled loop because it requires a variable that "counts by
one" on each execution of the loop. Therefore, besides the loop
statement, a counter-controlled loop requires a "counter" variable
that is:
1. initialized before the loop starts,
2. modified inside the loop, and
3. used in the decision expression to stop the loop.
The acronym I.T.E.M (Initialize, Test, Execute, and Modify) can
be used to check whether a loop and its counter variable are
being used correctly. Statements
to be
An example of a count-controlled loop that executes exactly 100 repeated
times is shown to the right. As you study this example, please
notice the following important points:
In this example, the "counter" variable is called "Count."
You can use any variable name, but try to make it
descriptive and meaningful for your current task.
8 of 15
The decision expression that controls the loop should typically test for "greater than or
equal to." This is a safer test than just "equal to."
The following three RAPTOR programs demonstrate common errors that should be avoided
when implementing loops. See if you can determine the error in each program. (If you can't find
the errors, they are explained in footnotes at the bottom of the page.) All three of these
problematic programs create an infinite loop – that is, a loop that never stops. To avoid writing
infinite loops, avoid these common errors.
2 3
The following example programs show the six (6) possible variations of a counter-controlled
loop. They all do the same thing -- they execute the statement(s) represented by the empty box
Limit number of times. You can use the variation that makes the most sense to you. In each
example, pay close attention to the starting (initial) value of Count and the Decision expression.
9 of 15
Start Start Start
Count ← Count + 1
Count > Limit Count >= Limit
Yes Yes
No No
No
Count ← Count + 1
Count ← Count + 1
Count ← Count + 1
Count >= Limit
Yes
No
No No
10 of 15
Input Loops
Sometimes you need a user to enter a series of values that you can process. There are two
general techniques to accomplish this. The first method is to have the user enter a “special”
value that signifies that the user is finished entering data. A second method is to ask the user, in
advance, how many values they will be entering. Then
that value can be used to implement a counter-controlled
loop. These two methods are depicted in the following
example programs. In both cases the empty boxes
signify where the entered data would be processed.
Don’t worry about how the data is processed, just look
at these examples to see how the user controls how
much data is entered.
Start
Sum ← 0
"Running Total" Loops
Another common use of loops is to calculate the sum of a
series of Loop data values, which is sometimes called a
"running total" or a "running sum." The example
program to the right produces a "running total" of a series of
values
"Please enter you data value. Enter 0 to stop."GET Value entered by a user.
Make sure you understand the assignment statement, Sum ← Sum + Value. In English it
says, calculate the expression on the right side of the arrow by taking the current value of Sum
and adding Value to it. Then place the result into the variable Sum.
The variable name, Sum, is not magic. Any variable name could be used, such as Total or
Running_Sum.
Start
"Counting" Loops
Another common use of loops is for Number_positive ← 0
previous example.
"Please enter you data value. Enter -999 to stop."GET Value
The last two examples demonstrate how
the same pattern of programming
statements occurs over and over again and
can be used to solve a variety of similar Value = - 999
Yes
problems. By studying and understanding
the simple examples in this reading you No
will be able to use these examples as the
basis for solving additional, more Yes
Value > 0
No
complex problems.
Number_positive ← Number_positive + 1
End
12 of 15
Summary
In this reading we have covered how to write Selection and Loop statements in RAPTOR.
Selection statements are used when you need to execute some statements while skipping others.
Loop statements are used to repeat a block of statements. If you are having a difficult time
determining whether to use a Selection statement or a Loop, it might be helpful to ask yourself
the following questions:
When developing Selection statements it is helpful to keep in mind the following questions:
Will the decision expression cause the correct statements to be executed?
Will the decision expression cause the correct statements to be skipped?
When developing Loops in your program it is helpful to keep in mind the following questions:
What statements do I need to repeat?
Have I initialized all variables correctly before the loop starts?
Will the Decision expression always evaluate to "Yes" at some time during execution?
If it is a counter-controlled loop, will it execute the correct number of times? (The most
common logic error in programming is an "off-by-one error," which means you want the
loop to execute N times, but it executes (N-1) or (N+1) times instead. Always check for
off-by-one errors as you are implementing your programs.)
13 of 15
What you have hopefully learned…
The ordering of programming statements is a key part of program development.
There are 3 basic types of program flow: Sequential, Selection, and Loop (Iteration).
When to use Selection statements and/or Loop statements for a particular problem
solving task.
Selection statements are used to execute or skip one or more programming statements.
Loop statements are used when one or more programming statements must be repeated.
The difference between "counter-controlled loops," "input loops," and "running total"
loops.
Infinite loops are bad and special care should be used to make sure your loops always
terminate.
Reading Self-Check
Which control structure would be most appropriate for the following problems:
Sequential, Selection, Cascading Selection, or a Loop
____________ Printing an appropriate message for a cadet’s class year.
____________ Checking for a correct input and continually re-checking if incorrect.
____________ Computing the average GPA of your CS110 section.
____________ Determining the volume of a sphere given a radius.
____________ Initializing all of the variables at the beginning of a program.
____________ Determining whether a vowel, constant or digit has been typed in.
____________ Writing out a message if an integer variable contains a negative value.
____________ Writing “Odd” or “Even” depending on an integer variable’s value.
____________ Writing out the squares of the numbers 1 though 100.
____________ Reading in scores until a user enters a negative number.
Which of the following Decision expressions will always evaluate to "Yes", always evaluate to
"No", or could possibly be either "Yes" or "No"?
14 of 15
Write a series of RAPTOR statements that determines if X has the value 1, 2, or 3, and prints
out “ONE”, “TWO”, or “THREE” accordingly.
Write a complete program that converts between degrees Fahrenheit and Celsius. The user must
first enter the conversion that is desired (F to C or C to F) using any means you want and then
enter the value to be converted. The formulas for conversion are:
F = 9/5 C + 32 and C = 5/9 (F – 32)
Write a complete program that plays the game of HI-LO. The program asks one user for a
number between 1 and 100 and verifies that such a number has been entered. It then asks a
second user for a guess and reads it in. If the guess is correct a congratulation message is
written to the screen and the program ends. Otherwise the message “HI” or “LOW” is displayed
(if the guess is higher or lower) and another guess is asked for and read in.
15 of 15