08 PRG1X1 - Decision Constructs & Loops
08 PRG1X1 - Decision Constructs & Loops
Objectives
– Define Repetition
– Types of Repetition
Decision Constructs
– A decision Construct, also knows as selection control structure, allows a
program to make a decision and change its behavior based on that decision.
If true:
If false:
Decision Constructs
– Decision Constructs can be represented in
algorithms as follows:
Decision to be made on a
question. Answer will either
be true/false, or Yes/No
Types of Decision Constructs
– We will look at 4 types of decision control structures:
a) if statement
b) if…else Statement
c) if…else…if statement
d) switch…case statement
a) if statement
An if statement consists of a
boolean expression which is
evaluated to a boolean value.
IF result == 2 THEN
PRINT "Result is 2“
END IF
IF result == 3 THEN
PRINT "Result is 3“
END IF
END
b) if…else statement
If the first if statement meet the result then code within the if block executes.
If not, control passes to the else statement, which contains a second "if" statement.
If second one meet the result then code within the if block executes.
A default else code block may execute when no condition has been evaluated to true.
b) if…else…if statement
Flowchart:
If…else statement
Example:
BEGIN
SET a = 6, b = 8;
SET result
result = a - b;
– This will stop the execution of more code and case testing inside the block.
– When a match is found, and the job is done, it's time for a break.
– A break can save a lot of execution time because it "ignores" the execution of
all the rest of the code in the switch block.
Repetition
– Presentation of a set of instruction to be performed repeatedly, as long as the condition
is true.
– Block statement is executed again and again until a terminating condition occurs
1. Counter Loops
a. For
b. While
c. Do…While
Explanation
Decrementing
1. Execute statement
DO
Execute statement 2. Starting at 10 || counter = 10 and counting Down
WHILE counter = 10 To 1 to 0 || counter > 0
END
3. Decrease by 1 each time || counter--
The Do…While Loop
Create an algorithm using pseudocode for a program that prints numbers from 10 to 1
Example:
BEGIN
SET num
DISPLAY “Enter number to display”
num = INPUT
FOR counter = 5 TO counter < 0
DISPLAY num
counter--
END FOR
END
Break (Stop Value)
– We have already seen the break statement used in an earlier when looking at
switch…case.
– It is used to “skip out" of a loop when a condition is met, and continues after.