Control Structures
Control Structures
The steps that are identified for preparing algorithms can be written using three basic control
structures or program constructs to indicate how instructions will be carried out or how the flow of
control from one statement to another will take place.
4. Statements involving the assignment of values variables through initialization, such as:
(a) Count 1
(b) Maximum 20
(c) Num1 0
1
The Selection Control Structure
The selection control structure is used in problems with instructions to be carried out if a certain
condition is met. The choice of options will be dependent on whether the condition it's true or false.
The control structure statements commonly used in algorithms are normally written as:
If (condition) then
Else
Endif
Example 2
Example 1
If (Age>=50) then
If (A>B) then Print “Old”
Display A Else
Else Print “Young”
Display B Endif
Endif
If (condition) then
Endif
Example
If (A>B) then
Display A
Endif
2
The Nested IF statement
The If/Elseif statement allows you to create a chain of if statements. The If statements are evaluated
in order until one of the expressions is true or the end of the If/Elseif chain is reached. If the end of
the If/Elseif chain is reached without a true expression, no code blocks are executed. The Nested
control structure statements commonly used in algorithms are normally written as:
If (condition 1) then
< Instructions to be performed if the condition 1 is true>
Elseif (condition 2) then
< Instructions to be performed if the condition 2 is true>
Elseif (condition 3) then
< Instructions to be performed if the condition 3 is true>
Else
< Instructions to be performed if the condition is false>
Endif
Example
Print “Please enter today’s temperature”
Get Temp
If (Temp >45) then
Print “Wear light weight rain coat”
Elseif (Temp>20) AND (Temp<45) then
Print “Wear soft shell jacket”
Elseif (Temp>0) AND (Temp<20) then
Print “Wear down jacket”
Else
Print “Wear base layers and down jacket”
Endif
3
Example of the While-do loop and Repeat-Until loop
Example
Display “Please enter Price of an item” Example
Read Price Repeat
While (price <> 0) do Display “Please enter Price of an item”
Total_Cost Total_Cost + price Read Price
Display “Please enter Price of an item” Total_Cost Total_Cost + price
Read Price Until (Price=0)
Endwhile Print Total_cost
Print Total_cost
<statements>
Endfor
Example 1
For (Count = 1 to 5) do
Display “Please enter Price of an item”
Read Price
Total_Cost Total_Cost + price
Endfor
Print Total_cost