Implementation: Algorithm specification Input validation algorithm

Algorithms are created to allow users to tell a computer how to solve a problem. Understanding how to construct three of the most common algorithms is a critical skill for budding software developers.

Part ofComputing ScienceSoftware design and development

Input validation algorithm

Input validation algorithms are used to check that input is acceptable.

Pre-test conditional loop

This example makes use of a pre-test conditional loop (While loop) and will check that a score entered by the user is between 1 and 99 inclusive.

A pre-test loop checks the conditions before the code within the loop is translated. If there is no need to execute the loop, the program will bypass lines three and four.

Line 1 RECEIVE score FROM (INTEGER) KEYBOARD
Line 2 WHILE score ˂ 1 OR score ˃ 99 DO
Line 3 SEND "Error, please enter a score between 1 and 99 inclusive" TO DISPLAY
Line 4 RECEIVE score FROM (INTEGER) KEYBOARD
Line 5 END WHILE

Post-test conditional loop

It is also possible to create an input validation algorithm using a post-test conditional loop.

A post-test conditional loop will execute all code within the loop at least once before checking the condition.

The example shown below will still check that the score entered is between 1 and 99 inclusive but makes use of a post-test loop (Until loop). When using a post-test conditional loop for input validation it is also necessary to use a selection statement, in this case an IF statement.

Line 1 REPEAT
Line 2 RECEIVE score FROM (INTEGER) KEYBOARD
Line 3 IF score ˂1 OR score˃ 99 THEN
Line 4 SEND "Error, please enter a score between 1 and 99 inclusive" TO DISPLAY
Line 5 END IF
Line 6 LOOP UNTIL score ˃=1 AND score ˂=99