#### Example 18 We'd like now to extend the design of the previous program and add one or two new features. It would be helpful if the program could give some clues and say whether the guess is too big or too small. It would also be helpful if the program could count the number of guesses and print the total at the end. We'll start our new design just like the original one: 1. Design a Solution 1. get number from player 1 2. get guess(es) from player 2 until guess is correct 3. print message Step 1 becomes: 1.1 prompt player 1 for number 1.2 read in number 1.3 clear the screen Step 3 becomes: 2.1 repeat 2.2 prompt player 2 for guess 2.3 read in guess 2.4 print clue 2.5 update number of guesses 2.6 until guess is correct Step 2.4 needs some clarification - note how the numbering system works... 2.4.1 if guess > number 2.4.2 then 2.4.3 print "guess is too big" 2.4.4 if guess < number 2.4.5 then 2.4.6 print "guess is too small" Step 3 becomes: 3.1 print message 3.2 print number of guesses So the complete solution is:

1.1 prompt player 1 for number 1.2 read in number 1.3 clear the screen 2.1 repeat 2.2 prompt player 2 for guess 2.3 read in guess 2.4.1 if guess > number 2.4.2 then 2.4.3 print "guess is too big" 2.4.4 if guess < number 2.4.5 then 2.4.6 print "guess is too small" 2.5 update number of guesses 2.6 until guess is correct 3.1 print message 3.2 print number of guesses

2. Code the Program As before, you should note that the whole point of designing the program is to make it easy to code. Check that the design above corresponds with the program below. type in the program

PROGRAM guessing; {a guessing game} VAR number : INTEGER; guess : INTEGER; total : INTEGER; BEGIN WRITE('enter the number to guess '); READLN(number); CLRSCR; REPEAT WRITE('enter your guess '); READLN(guess); IF guess > number THEN WRITELN('guess is too big'); IF guess < number THEN WRITELN('guess is too small'); total := total + 1; UNTIL guess = number; WRITELN('well done'); WRITELN('you took ', total, ' guesses') END.

save the program as guess2.pas compile and run the program This completes Part 1 of the tutorial, so well done if you've followed everything so far.
© 2001