Self-check questions
Write your answers first, then open the answers to check them.
- Why can pseudocode not be run on a computer, and why is it still useful?
- What is the difference between a WHILE loop and a REPEAT ... UNTIL loop?
- In Example 4, what is the sentinel value, and why is the first READ placed before the loop?
Show answers
It is not a real programming language: it has no strict syntax and no compiler or interpreter, so a computer cannot run it. It is still useful because you can plan the logic quickly in English-like steps that anyone can read, and then translate it into any programming language.
WHILEtests the condition before each pass (pre-test). The body may run zero times, and it repeats while the condition is true.REPEAT ... UNTILtests the condition after each pass (post-test). The body always runs at least once, and it repeats until the condition becomes true.
The sentinel is 0: a special value that means "stop" and is not part of the data. The first
READbefore the loop givesxa value to test. TheREADat the end of the body fetches the next value before the condition is tested again. If the first value is 0, the body never runs and the total is 0.
Practice exercises
- Write pseudocode to compute the factorial of N.
Hint
PseudocodeREAD n fact = 1 FOR i = 1 TO n DO fact = fact * i END FOR PRINT fact - Write pseudocode to print the first N Fibonacci numbers.
- Write pseudocode to count how many vowels are in a word.
- Write pseudocode to find the largest value in a list of N numbers.
Hint
READ the first value into
largest. Loop through the remaining N − 1 values; if a value is greater thanlargest, replace it. - Convert your flowchart from exercise 1.2 (question 5) into pseudocode.