Unit 11.3 Pseudocode - Iteration

Aims

  • Know what is meant by the term Iteration and the difference between count-controlled loops, pre-condition loops and post-condition loops.

  • Be able to write pseudocode that uses a for loop, while loop and a repeat loop.

Iteration (aka Looping) is when 1 or more lines of code are run more than once, making either a Count-Controlled Loop, repeats code a fixed number of times (for Loop) or Condition-Controlled Loop, repeats code until a condition has been met (Pre-Condition - While Loops or Post-Condition (Repeat Loops)

For Loops - Count Controlled

Repeats section of code a fixed number of times

Syntax to be used - FOR Loops

E.g. FOR count1 to 10

OUTPUT “Hello”

NEXT count

Identifier must be a variable with a data type integer, the variable is assigned each of the integer values from value to Value2 inclusive, running the statements inside the for loop after each assignment, if Value=value2 the statements are executed once, if value > Value 2 the statements wont be executed.

Each time a FOR loop is run, the identifier is incremented by one, this can be changed using STEP command e.g. this will loop output 5 times (1,3,5,7,9)

FOR count ←1 TO 10 STEP 2

OUTPUT “Hello”

NEXT Count

WHILE Loops - Pre Condition

Tests condition at start of loop, if condition is met it wont run the loop, if it isn’t met, then the code inside the loop will run

Syntax to be used WHILE Loop:

E.g. While Loop continually output “Hello” while count is <= 10

DECLARE count : INTEGER

count ← 1

WHILE count <= 10

OUTPUT “Hello”

count ← count + 1

ENDWHILE

Condition must be an expression with a BOOLEAN outcome (True/False), condition is tested before statements are run and only executed if condition is true.

After statements are executed, condition is tested again, loop stops when condition is false, statements aren’t executed if the condition is false on the first run.

Repeat Loops - Post Condition

Tests conditions at end of the loop meaning the code inside the loop is run at least once.

Syntax for REPEAT loops:

E.g. Repeat loop continually outputting “Hello” while count is <=11

DECLARE count : INTEGER

count ← 1

REPEAT

OUTPUT “Hello”

count ← count + 1

UNTIL count = 11

Condition must be Boolean outcome (T/F) statement in loop is executed at least once, condition is tested once statements are executed and terminates if the condition is true or executed again if condition is false.