Selection statements (sometimes called conditional statements) can be defined as code (statements) that is executed only when a certain condition is satisfied. Selection is a powerful tool to control when and which code statements will run.
Think of selection as the situations in programming where we need our code to branch out (flow differently), taking different paths depending upon a condition.
For example, imagine losing a life in a computer game. The program will need to decide whether to allow us to start playing the level again, or to show the game over screen. The path chosen in this situation will depend upon how many lives we have left. So, the condition to select the appropriate code to run may be ‘is lives > 0’.
There are 2 types of selection that you need to learn for GCSE:
- IF.. THEN .. ELSE .. ENDIF
- CASE .. OF .. OTHERWISE .. ENDCASE
Programming languages may put their own syntax/wording on these selection structures, but look closely and you’ll see that they do relate back to the above list.
IF.. THEN .. ELSE .. ENDIF
A logical condition is tested.
A positive (true) outcome will result in the THEN statements of code being executed.
A negative (false) outcome will result in the ELSE statements of code being executed.
CASE .. OF .. OTHERWISE .. ENDCASE
A series of statements (options) are programmed to take into account the testing of a condition that may have many outcomes.
For example, 7 code options (statements) could be programmed to fulfill a condition that checks to see what the current day of the week is.