Reference languageUse of IF condition/selection statement

It is important to read and understand a formal language. Declaring variables and data types, using selection statements, iteration and using operators are comprehensions required before coding.

Part ofComputing ScienceSoftware design and development

Use of IF condition/selection statement

IF pass = true THEN
SEND “Well done, you have passed” TO DISPLAY
END IF

In the following example it is necessary to use the ELSE command because the statement has two possible selections/outcomes.

IF pass = true THEN
SEND “Well done, you have passed” TO DISPLAY
ELSE
SEND “Unfortunately, you did not pass the test” TO DISPLAY
END IF

Iteration v repetition (loops)

Iteration takes place when the values held within an array are used/examined/processed in order, one after the other.

Repetition is any other form of loop that repeats a series of commands a set number of times. Repetition can be both fixed and conditional.

Iteration – FOR loops

It is important to note that indexing starts from 0 and not 1, unless otherwise stated. This can be seen here where the counter is set to repeat ten times (0 TO 9 rather than 1 TO 10).

FOR counter FROM 0 TO 9 DO
IF score [counter] > maximum THEN
SET maximum TO score[counter]
END IF
END FOR

The other version of a FOR loop is more generic in nature as there is no requirement to set the lower and upper bounds of the index.

FOR EACH score FROM allScores[] DO
IF score > maximum THEN
SET maximum TO score
END IF
END FOR EACH

This would take each score held in the array allScores in order and perform the commands found within the loop.

Repetition – fixed repetition (REPEAT)

The distinction between fixed repetition and iteration is that fixed repetition can repeat a set of commands without needing to iterate over the values of a data structure like an array.

REPEAT 5 TIMES
SEND “Game Over” TO DISPLAY
END REPEAT

This would send the string text 'Game Over' to the display five times:

Game Over
Game Over
Game Over
Game Over
Game Over

Repetition – conditional repetition (WHILE and REPEAT…UNTIL)

There are two forms of conditional repetition. The first is known as pre-condition repetition and will only allow the loop to execute if the condition it is set up to check is true. For this purpose a WHILE loop can be used.

WHILE percentage <0 OR percentage >100 DO
SEND “The percentage you entered is not valid. Please try again.” TO DISPLAY
RECEIVE percentage FROM (REAL) KEYBOARD
END WHILE

The loop will only execute if the value of the percentage variable is less than 0 or greater than 100.