PROGRAM CONTROL STRUCTURES
Control structures are blocks of statements that determine how program statements are to be
executed.
Control statements deal with situations where processes are to be repeated several number of
times or where decisions have to be made.
There are 3 control structures used in most of the structured programming languages:
1). Sequence.
2). Selection.
3). Iteration (looping).
SEQUENCE CONTROL STRUCTURES
In Sequence control, the computer reads instructions from a program file line-by-line starting
from the first line sequentially towards the end of the file. This is called Sequential program
execution.
Start Statement 1 Statement 2 … Statement n End
Note. Sequential program execution enables the computer to perform tasks that are arranged
consecutively one after another in the code.
SELECTION (DECISION) CONTROL STRUCTURES
Selection involves choosing a specified group of instructions/statements for execution.
In Selection control, one or more statements are usually selected for execution depending on
whether the condition given is True or False.
The condition must be a Boolean (logical) expression, e.g., X >= 20
In this case, the condition is true if x is equal to or greater than 20. Any value that is less than 20,
will make the condition false.
Generally, there are 4 types of selection control structures used in most high-level programming
languages:
1). IF – THEN
2). IF – THEN – ELSE
3). Nested IF
4). CASE – OF
Note. These control structures are used in a program based on a sequence of instructions, which
require that a choice (decision) be made between two or more alternatives.
In such a situation, the computer must be programmed to compare data, and take action
depending on the outcome of the comparison.
IF – THEN
IF – THEN structure is used if only one option is available, i.e., it is used to perform a certain
action if the condition is true, but does nothing if the condition is false.
The general format of the IF-THEN structure is:
IF < Condition > THEN
Program statement to be executed if condition is true;
ENDIF
1
If the condition is TRUE, the program executes the part following the keyword ‘THEN’. If the
condition is FALSE, the statement part of the structure is ignored, and the program continues
with the statements below the ENDIF.
The diagrammatic expression of the IF-THEN structure is:
FALSE
Conditio
TRUE
Execute statements between
THEN & ENDIF
Continuation of program
Example 1;
In a school, the administration may decide to reward only those students who attain a mean mark
of 80% and above.
Flowchart
Pseudocode
IF Mark > 80 THEN
Print “ Give reward” Mark Yes
> 80
ENDIF
No Print reward
Stop
Example 2;
A user is asked to enter a set of positive numbers, one at a time. She enters a 0 (zero) to indicate
that she has no more numbers to enter.
Develop an algorithm to print the largest number entered.
Pseudocode
START
Prompt the user for a number, Largest
Prompt the user for another number, NewNumber
IF NewNumber > Largest THEN
Set Largest to NewNumber
ENDIF
Prompt the user for a number, NewNumber
Output (‘The largest number entered is’, Largest)
STOP
2
As each number is entered, the algorithm checks if the number entered is larger than the previous
ones. If it is larger, it is saved as the largest. If it is smaller, it is ignored, and holds onto the
largest number so far.
Example 3;
PROGRAM AgeTalk (Input, Output);
VAR Age: INTEGER;
BEGIN {program}
Writeln (‘How old are you?’); Readln (Age);
IF Age >= 18 THEN
Writeln (‘You are old enough to join the army.’);
END. {program}
Note. Compound statements can also be used with the IF – THEN structure.
Example 4;
PROGRAM Service; {*This program displays a message depending on the number of
years you have worked for a company*}
VAR Years: INTEGER;
BEGIN
CLRSCR
Writeln (‘How long have you been with the company?’); Readln (Years);
IF Years > 20 THEN
Writeln (‘Get a Gold watch’);
IF (Years > 10) AND (Years <= 20) THEN
Writeln (‘Get a Paper weight’);
IF Years <= 10 THEN
Writeln (‘Get a pat on the back ’);
END.
IF – THEN -ELSE
The IF-THEN-ELSE structure is suitable when there are 2 available options to select from.
The general format of the IF-THEN-ELSE structure is:
IF < Condition > THEN
Statement 1; (called the THEN part)
ELSE
Statement 2; (called the ELSE part)
ENDIF (indicates the end of the control structure)
3
The diagrammatic expression of the IF-THEN-ELSE structure is:
TRUE FALSE
Conditio
Execute statements between Execute statements between
THEN & ELSE ELSE & ENDIF
Execute statements after
ENDIF
Continuation of program
When the IF-THEN-ELSE structure is encountered:
1). The Condition is tested.
2). If the Condition is TRUE, the statements between THEN & ELSE (i.e., the THEN part) are
executed.
The ELSE part is skipped, and execution continues with the statement following ENDIF.
3). If the Condition is FALSE, the THEN part is skipped. The statements between ELSE &
ENDIF (i.e., the ELSE part of the structure) are executed, and execution continues with the
statement following ENDIF.
After either group of statements has been executed, the program will then continue executing the
program statements after the last ENDIF.
Note. Using IF-THEN-ELSE, for any given test of the condition, only one set of statements is
selected for execution (not both statements).
Example 1;
In a football match, if a player makes a mistake which is considered serious by the rules of the
game, he/she is given a Red card. Otherwise, he/she is given a Yellow card.
Flowchart
Pseudocode
IF Fault = Serious THEN
Print “ Give red card” No Fault Yes
ELSE =
Print “ Give Yellow card”
Print Yellow Print Red
ENDIF card card
Example 2;
Write an algorithm which asks a user for two numbers; A and B, and calculates the value of A
divided by B. However, if B is 0, a message is printed which says that division by 0 is not
allowed.
4
Pseudocode
START
Prompt the user for the two numbers, A and B
IF B = 0 THEN
Writeln (‘Division by 0 is not allowed’) ELSE
Set C to A/B
ENDIF
Output A, B, and C
STOP
Explanation.
Suppose the user enters 1 for A and 0 for B in response to the prompt.
The algorithm will test if B=0. Since B is 0, the condition is True. Therefore, the THEN part
is executed printing the message: ‘Division by 0 is not allowed’.
Suppose the user enters 20 for A and 5 for B in response to the prompt.
The algorithm will test if B=0. Since B is not 0, the condition is False. Therefore, the
statements between ELSE & ENDIF are executed (i.e., A is divided by B, and the result is
stored in C).
NESTED IF
Nested IF structure is used where 2 or more options have to be considered to make a selection.
The general format of the Nested IF structure is:
IF < Condition 1 > THEN
Statement 1
ELSE
IF < Condition 2 > THEN
Statement 2
ELSE
IF < Condition 3 > THEN
Statement 3
ELSE
Statement 4;
ENDIF
ENDIF
ENDIF
Example;
In an Olympics track event, medals are awarded only to the first three athletes as follows:
a). Position 1: Gold medal
b). Position 2: Silver medal
c). Position 3: Bronze medal
The pseudocode and flowchart below can be used to show the structure of the Nested IF
selection.
5
Pseudocode
IF Position = 1 THEN
Medal = “Gold”
ELSE
IF Position = 2 THEN
Medal = “Silver”
ELSE
IF Position = 3 THEN
Medal = “Bronze”
ELSE
Medal = “nil”
ENDIF
ENDIF
ENDIF
Flowchart
No No No
Positio Positio Positio
n1 n2 n3
Yes Yes Yes
Medal = Medal = Medal = Medal =
“Gold” “Silver” “Bronze” “Nil”
Print medal
When IF statements are embedded within one another, they are said to be Nested.
Note. Each IF-THEN or IF-THEN-ELSE is terminated with the comment {ENDIF}. The
number of {End If’s} must be equal to the number of ELSE’s.
The CASE structure
CASE-OF allows a particular group of statements to be chosen from several available groups.
It is therefore used where the response to a question involves more than two choices/alternatives.
The general format of the CASE structure is:
CASE Expression OF
Label 1: statement 1
Label 2: statement 2
Label 3: statement 3
6
.
.
.
Label n: statement n
ELSE
Statement m
ENDCASE
√ The Boolean expression for the CASE structure can only be expressed using Integers or
alphabetic characters only. Hence;
CASE Integer OF or CASE Char OF
√ A statement is executed only if one of its corresponding labels matches the current value of
the expression. This implies that, the current value of the expression determines which of the
statements will be executed.
Example 1;
Write a pseudocode of a program that requests the user to type a number from 1 to 7. The
program then prints the corresponding day of the week.
Pseudocode
START
Prompt the user for a number from 1 to 7, Day
CASE Day OF
1: Writeln (‘Sunday’);
2: Writeln (‘Monday’);
3: Writeln (‘Tuesday’);
4: Writeln (‘Wednesday’);
5: Writeln (‘Thursday’);
6: Writeln (‘Friday’);
7: Writeln (‘Saturday’);
ENDCASE
STOP
The CASE structure consists of:
The word CASE.
A Control variable (e.g., Day).
The word OF.
A group of one or more statements, each group labeled by one or more possible values of the
control variable.
The word ENDCASE, indicating the end of the construct.
When a CASE statement is encountered, the value of the control variable is used to determine
which group of statements is executed, e.g., if the value of Day is 5, then the group of statements
labeled 5 is selected for execution, and the statement; ‘Thursday’ is printed.
After executing this group of statements, execution continues at the statement following
ENDCASE.
7
NOTES:
i). The programmer should ensure that the value of the control variable appears as a label.
E.g., suppose the value entered for Day was 9. Since 9 does not label any statement within
the CASE construct, an error will result.
ii). A given label can be used on only one group of statements. E.g., 5 can’t be used to label
two groups of statements. If this is done, the computer will not know which group to select
& unpredictable results can occur.
Example 2;
Write a pseudocode of a program that requests the user to type a number from 1 to 7. Depending
on the number entered, print the message, ‘It is a School day’ or ‘It is on a Weekend’.
Pseudocode
Prompt the user for a number from 1 to 7, Day
IF (Day < 1) OR (Day >7) THEN
Print (‘Invalid number entered ---’, Day)
ELSE
CASE Day OF
2, 3, 4, 5, 6: Writeln (‘It is a School day’);
1, 7: Writeln (‘It is on a Weekend’);
ENDCASE
ENDIF
STOP
In this pseudocode, the IF statement has been used to validate the value of Day. This ensures
that, only valid data gets processed by the CASE statement.
Otherwise, if the ELSE part is executed, we are sure that the value of Day will lie between 1 and
7 inclusive.
Example 3;
Pseudocode
CASE Average OF
80 .. 100: Grade = ‘A’
70 .. 79: Grade = ‘B’
60 .. 69: Grade = ‘C’
50 .. 59: Grade = ‘D’
40 .. 49: Grade = ‘E’
ELSE
Grade = ‘F’
ENDCASE
8
Flowchart
Averag No AVG No AVG No AVG No
e 70 - 60 - 50 -
Yes Yes Yes Yes
Grade = A Grade = B Grade = C Grade = D Grade = E
PRINT Grade
Example 4;
PROGRAM CaseSample (Input, Output);
VAR Grade:CHAR;
BEGIN {Program}
Writeln (‘What grade did you get?’); Readln (Grade);
CASE Grade OF
‘A’, ‘B’ : Writeln (‘Very Good’);
‘C’ : Writeln (‘Pass’);
‘D’, ‘F’ : Writeln (‘Wake up’);
End; {Case}
Readln;
End. {Program}
ITERATION (LOOPING / REPETITION) CONTROL STRUCTURES
Looping refers to the repeated execution of the same sequence of statements to process
individual data. This is normally created by an unconditional branch back to a previous/earlier
operation.
The loop is designed to execute the same group of statements repeatedly until a certain condition
is satisfied.
Note. Iteration is important in situations where the same operation has to be carried out on a set
of data many times.
The loop structure consists of 2 parts:
1). Loop body, which represents the statements to be repeated.
2). Loop control, which specifies the number of times the loop body is to be repeated.
Types of loops:
(a). Conditional loop: - This is where the required number of repetitions is not known in
advance.
9
Pseudocode
STEP 1: [Prompt the user for temperature in oC]
STEP 2: [Store the value in memory]
STEP 3: IF C = 0 THEN Stop
STEP 4: [Calculate temperature in oF]
F: = 32 + (oC * 9/5)
STEP 5: [Output temperature in oC & oF]
STEP 6: [GOTO Step 1]
Flowchart
STAR
Prompt the user
to enter Temp. in
o
C
Store the value in
Loop
memory
YES
Is C = STOP
NO
Calculate Fahrenheit
F = 32 + (9/5 * oC)
Output the
temp. in oC & oF
This algorithm illustrates Conditional execution. Conditional execution is a situation that
requires that a logical test be carried out, and then a particular action be taken depending on
the outcome of that test.
In this case, going to Step 4 will depend on whether the condition is True or False. E.g., If
C = 10 then the condition ‘C = 0’ is False, and the program goes to Step 4. But if C = 0,
then the condition is True, and the program stops.
(b). Unconditional loop: - This is where the execution of the instructions is repeated some
specified number of times.
(c). Continuous (infinite/unending) loop: - This is where the computer repeats a process again
and again, without ending.
Example:
STEP 1: [Prompt the user for temperature in oC]
STEP 2: [Store the value in memory]
10
STEP 3: [Calculate temperature in oF]
F: = 32 + (oC * 9/5)
STEP 4: [Output temperature in oC & oF]
STEP 5: [GOTO Step 1]
As long as a number is entered for oC, the algorithm does not stop when it reaches STEP 5
but rather transfers control to STEP 1, causing the algorithm/process to be repeated.
However, a zero (0) can be used to stop the program because; the program cannot give the
Fahrenheit equivalent to 0 oC.
Requirements for loops:
1. Control variable (Counter): - it tells/instructs the program to execute a set of statements a
number of times.
2. Initialization: - allocating memory space, which will be occupied by the output.
3. Incrementing: - increasing the control variable by a certain number before the next loop.
Generally, there are 3 main looping controls:
1. The WHILE loop
2. The REPEAT…UNTIL loop.
3. The FOR loop.
The FOR loop
The FOR loop is used in situations where execution of the chosen statements has to be repeated a
predetermined number of times.
The general format of the FOR loop is:
FOR loop variable = Lower limit TO Upper limit DO
Statements;
END FOR
The flowchart extract for a FOR loop that counts upwards is:
Lower limit = Loop variable + 1
Loop variable = Lower limit Statements
NO
Condition
YES
Example;
Consider a program that can be used to calculate the sum of ten numbers provided by the user.
The ‘FOR’ loop can be used to prompt the user to enter the ten numbers at most 10 times. Once
the numbers have been entered, the program calculates and displays the accumulated sum.
11
Pseudocode Flowchart
FOR count = 1 TO 10 DO
PRINT “Enter a number (N)” Lower limit = Count + 1
Sum = Sum + N
END FOR
Count = Lower limit Sum = Sum + N
Display SUM
Coun YES
t <=
NO
Sum
Explanation
1. The loop variable (Count) is first initialized/set to the Lower limit whose value is 1.
2. The lower limit is then tested against the Upper limit whose value is set at 10.
3. If the lower limit is less than or equal to 10, the program will prompt the user to enter a
number N, otherwise the computer will exit the loop.
4. After the last statement in the loop has been executed, the loop variable (count) is
incremented by a 1 and stored in the lower limit, i.e., Lower limit = Count + 1.
5. The lower limit is again tested, and if it is less than or equal to 10, the loop is repeated until
the time the lower limit will equal the upper limit.
NOTE:
The FOR loop can also be used to count downwards from the upper limit to the lower limit.
E.g., FOR count = 10 DOWN TO 1DO
In this case, the upper limit 10 is tested against the lower limit 1.
Pseudocode for a ‘FOR’ loop that counts from upper limit down to the lower limit:
FOR loop variable = Upper limit DOWN TO Lower limit DO
Statements;
END FOR
The flowchart extract for a FOR loop that counts downwards is:
Upper limit = Loop variable - 1
Loop variable = Upper limit Statements
NO
Condition
YES
12
The WHILE loop
The ‘WHILE’ loop is used if a condition has to be met before the statements within the loop are
executed.
E.g., to withdrawal money using an ATM, a customer must have a balance in his/her account.
Therefore, it allows the statements to be executed zero or many times.
Pseudocode Flowchart
WHILE Balance > 0 DO
Withdraw cash
Update account Withdraw cash
Update account
ENDWHILE
YES
Balance >
NO
Exit loop
Explanation
1. The condition balance > 0 is first tested.
2. If it is TRUE, the account holder is allowed to withdraw cash.
3. The program exits the loop once the balance falls to zero.
The general representation of the WHILE loop is:
Pseudocode segment Flowchart extract
WHILE Condition DO
Statements;
ENDWHILE Statements
TRUE
Condition
FALSE
Exit loop
The REPEAT…UNTIL loop
In REPEAT…UNTIL, the condition is tested at the end of the loop. Therefore, it allows
statements within it to be executed at least once.
E.g., if REPEAT…UNTIL is used in case of the ATM cash withdrawal, the customer will be
able to withdraw the cash at least once since availability of balance is tested at the end of the
loop.
13
Pseudocode Flowchart
REPEAT
Withdraw cash
Update account Withdraw cash
Update account
UNTIL balance <= 0;
Yes
Balance >
No
Exit loop
The general format of the REPEAT…UNTIL loop is:
Pseudocode segment Flowchart extract
REPEAT
Statements; Repea
UNTIL Condition;
Statements
True
Condition
False
Exit loop
DEVELOPING COMPLEX ALGORITHMS
14
Example 1:
With aid of a pseudocode and a flowchart, design an algorithm that:
a). Prompt the user to enter two numbers X and Y.
b). Divide X by Y. However, if the value of Y is 0, the program should display an error message
“Error: Division by zero”.
Pseudocode
START
PRINT “Enter two numbers X and Y”
INPUT X, Y
IF Y = 0 THEN
PRINT “Error: Division by zero”
ELSE
Quotient = X/Y
PRINT X, Y, Quotient
ENDIF
STOP
Flowchart
Start
X,
Y
Yes
Is Y = Error: Division by 0
No
Quotient = X/Y
X, Y,
Quotient
Stop
Example 2:
In an athletics competition, an athlete is rewarded as follows:
1st position: Gold
2nd position: Silver
3rd position: Bronze
Draw a pseudocode and a flowchart for a program that would be used to determine the type of
medal to be rewarded to each athlete.
Pseudocode
15
START
PRINT “Enter athlete Name and Position”
INPUT Name, Position
IF Position = 1 THEN
Medal = “Gold”
ELSE
IF Position = 2 THEN
Medal = “Silver”
ELSE
IF Position = 3 THEN
Medal = “Bronze”
ELSE
Medal = “None”
ENDIF
ENDIF
ENDIF
Flowchart
Start
Name, Position
No No No
Repeat
Positio Positio Positio
n 1? n 2? n 3?
Yes Yes Yes
Medal = Gold Medal = Silver Medal = Bronze Medal = “None”
PRINT Name, Position, Medal
No
Exit
Yes
Stop
Example 3:
16
The class teacher of Form 3S in a secondary school requested a programmer to design for her a
simple program that would help her do the following:
(a) Enter the names of students and marks obtained in 8 subjects – Mathematics, English,
Kiswahili, Biology, Chemistry, Business studies, Computer studies, and History.
(b) After entering the mark for each subject, the program should calculate the total and average
marks for each student.
(c) Depending on the Average mark obtained, the program should assign grade as follows:
(i) Between 80 and 100 – A
(ii) Between 70 and 79 – B
(iii) Between 60 and 69 – C
(iv) Between 50 and 59 – D
(v) Below 50 –E
(d) The program should then display each student’s Name, Total marks and the Average grade.
Using a pseudocode and a flowchart, write an algorithm that shows the design of the program.
Pseudocode
START
REPEAT
PRINT “Enter student Name and subject marks”
INPUT Student name, Maths, Eng, Kisw, Bio, Chem, Business, Computer, History
SUM = Maths + Eng + Kisw + Bio + Chem + Business + Computer + History
AVG = SUM/8
IF (AVG => 80) AND (AVG <= 100) THEN
Grade = “A”
ELSE
IF (AVG => 70) AND (AVG <= 79) THEN
Grade = “B”
ELSE
IF (AVG => 60) AND (AVG <= 69) THEN
Grade = “C”
ELSE
IF (AVG => 50) AND (AVG <= 59) THEN
Grade = “D”
ELSE
Grade = “E”
ENDIF
ENDIF
ENDIF
ENDIF
PRINT Student name, Sum, AVG, Grade
UNTIL Count = Number of students
STOP
17
Flowchart
Start
ENTER Student
name, Maths, Eng,
Kisw, Bio, Chem,
Business, Computer,
History
Repeat
SUM = Maths + Eng + Kisw
+ Bio + Chem + Business +
Computer + History
No AVG No AVG No AVG No
AVG
80 - 70 - 60 - 50 -
Yes Yes Yes Yes
Grade = A Grade = B Grade = C Grade = D Grade = E
Student name, Sum, AVG, Grade
No
Exit
Yes
Stop
Example 4:
The gross salary of employees in ZAG BOOKS ENTERPRISE is based on basic salary and
additional benefits as follows:
(a) Employees who have worked for the company for more than 10 years receive an additional
pay of 10% to their basic salary.
(b) Monthly salary bonus based on monthly sales of books as follows:
Monthly sales Bonus Rate (%)
Above 500,000 15
Between 250,000 and 500,000 10
Below 250,000 5
Draw a flowchart for a program that would be used to calculate the gross salary then output each
employee’s basic salary, gross salary and all benefits.
18
Start
ENTER Name,
Basic, Sales, Years
Experienc Yes
Benefit = Basic x 0.1
e > 10 Yrs
Sales Yes
Bonus = Sales x 0.15
>
No
Repeat
Bonus = Sales x 0.05 Yes Sales No Bonus = Sales x 0.1
<
Gross = Basic + Benefit + Bonus
PRINT Name, Gross, Basic, Benefit, Bonus
Exit
Stop
Example 5:
A lady deposits 2,000 shillings in a Microfinance company at an interest rate of 20% per annum.
At the end of each year, the interest earned is added to the deposit and the new amount becomes
the deposit for that year.
Write a pseudocode for a program that would track the growth of the deposits over a period of
seven years.
19
START
INPUT Initial Deposit
INPUT Interest Rate
SET Deposit to Initial deposit (i.e., 2000)
SET Year to 0
WHILE Year <= 7 DO
Interest = Deposit x Interest rate
Total = Deposit + Interest
Deposit = Total {the new deposit}
Year = Year + 1
ENDWHILE
PRINT Deposit, Year
STOP
Example 6:
Draw a flowchart for a program that is to prompt for N numbers, accumulate the sum and then
find the average. The output is the accumulated totals and the average.
BEGI
Initialize Sum =0
Count = 0
Enter a number N
Sum = Sum + N
Count = Count + 1
Average = Sum / Count
NO
N
YES
PRINT Sum, Average
EN
Example 7:
Mutuku took a loan of Ksh. 400,000 from a local bank at an interest rate of 10% payable in four
years. Assuming you wish to develop a computer program that will keep track of monthly
repayments:
(a) Identify the input, processing and output requirements for such a program.
(b) Design the algorithm for the program using a simple flowchart and pseudocode.
20
(a). Requirements:
Input - Initial amount borrowed
- Interest rate
- Number of years
Processing - equation to calculate Yearly repayments and Monthly repayments.
Output - Monthly repayments calculated by the process
(b). Pseudocode:
START
INPUT Initial amount borrowed
INPUT Interest rate
INPUT Number of years
Calculate Yearly repayments
Monthly repayments = (Yearly repayments / 12)
OUTPUT Monthly repayments
STOP
Flowchart:
BEGIN
ENTER Initial amount, Interest
rate, number of Years
Calculate Yearly
repayments & Monthly
repayments
PRINT Monthly repayments
END
21