Writing control structures in pseudocode

The simplest control structure is the sequence. You have been writing pseudocode with those since the very first design. But you need to know how to write other control structures in pseudocode. Not all designs are just sequences! To show that you are creating an if/selection/branch structure, your pseudocode should look something like:

	     if the input value is > 0
		     output message "positive"
		     set pflag to true
		     add input value to ptotal
	     else
		     output message "negative"
		     set pflat to false
		     add input value to ntotal

An if structure that didn't need an else would look like:

	     if leg1 + leg2 < hyp 
		     output "a triangle"
		     area is leg1 * leg2 / 2

The indentation is really necessary to show to a quick glance that these two steps are depending on the step above them.

A longer example:

	     set correct counter to 0
	     get two random numbers from 1 to 10
	     display the random numbers to the user as an addition problem
	     input an answer from the user
	     if answer is correct
		     output correct message
		     add 1 to correct counter
	     else
		     tell the user incorrect message
		     give user another chance at getting the answer
		(which would have more detail at a deeper level)
	     tell user goodbye

If you wanted to repeat steps in a loop control structure, it would look like this:

	     set try counter to 1
	     get a random number from 1 to 50
	     ask the user for a guess for the random number
	     input a guess from the user
	     while the guess is not correct
		     tell the user it's not right
		     add one to try counter
                     if guess is less than the random number  
                            tell the user "you're low"
                     else
                            tell the user "you're high"
		     ask for another guess
	     output the try counter "You took " this many " tries"

The way that the statements are indented show that they are in the body of the loop.

Another example of a loop

         ask user "how many generations to simulate?" store in numgens
         ask for file containing initial generation
         use numgens to control a loop (as final value)
                 find new generation from old generation
                 display new generation
                 copy new generation to old generation
                 add one to loop control variable
         say goodbye