Just like with flowcharts where you can repeat a series of steps, you can repeat a series of steps in pseudocode. And just like with Flowcharts, we have two main types of repetition, conditional loops and counting loops. In this example we are going to work with conditional loops.
Setting the Condition
First we need to start with what our condition will be. It needs to be answered in a true/false or yes/no style of format.
A very general form might be something like:
while users selects to continue
A more programatic way might be:
while userContinue = true
Depending upon who you are writing for will dictate which version to use. As I write for a lot of new developers, I often use the second option, however both should still be clear. With Psuedocode, we don’t have to be as precise as with a flowchart, but we don’t want to get “sloppy” in our code either.
Remember, it is easier to write a condition that is true, than false.
# easier to read
while file has more data
# harder to read/easier to make mistakes with
while file end not reached
# or, and this is worse -
while file end = false
Both of these do the same thing, but the not
is an easy word to forget, overlook, and can completely change the meaning.
The Loop Body
As with the example of making decisions in pseudocode, we will often indent the body of our loop, so we know what section is being repeated. This is important as a loop body can be many lines long, or just a single line
while salesAmount >= 0
runningTotal += salesAmount
prompt salesAmount = "What is the total"
print "The total sales amount is: " + runningTotal
When wondering how many lines of code, the answer is “enough to solve the problem”. So make sure you are clear. Once you are done with the loop, you no longer have to indent.
Some people recommend putting a key word like loop
at the end of the loop. While you can do this, I, as do most people, find that simply indenting the loop body is enough to tell the user what to do.
When you are at the end of the body, you go back to your initial condition and check to see if it is still met. This means you need to update the values of your condition to ensure you don’t get stuck in an infinite loop – that is a loop that you cannot exit from.
Conditional Repetition with Pseudocode was originally found on Access 2 Learn
One Comment
Comments are closed.