How to write pseudocode

 

There are six basic computer operations

some action

                        ELSE

                                    alternative action

                        ENDIF

 

some action

                        ENDWHILE

some action

                        ENDFOR


The Structure Theorem

          (and the pseudocode we use to represent the control structures)

 

            It is possible to write any computer program by using only three basic control structures: sequence, selection, repetition.

 

Sequence

            Execution of one step after another. This is represented as a sequence of pseudocode statements:

            Statement 1

            Statement 2

            Statement 3

 

Example:

            Read three numbers

            Add three numbers

            Display total of three numbers

 

Selection

            Presentation of a condition and the choice between two actions, the choice depending on whether the condition is true or false.  This construct represents the decision making abilities of the computer to compare two pieces of information and select one of two alternative actions.  In pseudocode, selection is represented by the keywords IF, THEN, ELSE and ENDIF

 

            IF condition p is true THEN

                        statement(s) in true case

            ELSE

                        statement(s) in false case

            ENDIF

 

Example:

 

            IF student is part_time THEN

                        Add one to part_time_count

            ELSE

                        Add one to full_time_count

            ENDIF

 

A variation – We don’t need the ELSE structure – The null ELSE

 

            IF condition p is true THEN

                        statement(s) in true case

            ENDIF

 

Repetition

 

            Presentation of a set of instructions to be performed repeatedly, as long as a condition is true.

           

            WHILE condition p is true

                        Statement(s) to execute

            ENDWHILE

 

The condition is tested before any statements are executed.  It is imperative that at lease one statement within the statement block alter the condition and eventually render it false, otherwise the logic may result in an endless loop.

 

Example:

 

            Set student_total to 0

            WHILE student_total < 50

                        Read student record

                        Print student name and address

                        Add 1 to student_total

            ENDWHILE

 

Note: The variable student_total is initialized before the loop condition is executed

            The student_total variable is incremented within the body of the loop so it will eventually stop.  These are both essential feature of the WHILE construct.