Computers are excellent at doing the same operation over and over again -- people frequently are not. We can also get the computer to wait around until the user supplies a valid input, i.e., no letters in something that we plan on being an integer. This is an ideal situation for using a Repeat-Until loop, because we know that the loop must be executed at least once to get a good value from the user. If we don't get one, we ask again.
We will use another modification of the area-of-a-triangle program to illustrate this. The problem and pseudocode are as follows:
The Problem: Write a program to calculate the area of a triangle, allowing only positive values to be entered for the base and height.
The Pseudocode:
1. Simple introduction and instructions;
2A. Repeatedly
a) get the base
while not positive;
2B. Repeatedly
a) get the height
while invalid or not positive;
3. Calculate the area;
4. Print out the results.
Please note that the loops for getting the base and height are NOT the same. Both begin by prompting the user for a value.
For the base, we here assume that the user will not input any invalid characters. If the value given for the base is not positive, we simply request another.
Because users frequently mistype things, the loop for obtaining the value for the height also checks to make sure that only characters that are acceptable for an integer have been typed. val() reports in its third parameter which character was found to be illegal.
program TriangleWait (input, output);
var
b, h: integer; {Base & Height}
A: real; {Area}
h_string : string; {Input string for Height}
Err : integer; {Error flag set by Val()}
begin
{------------Introduction & Setup------------------}
writeln('This program calculates and prints the area of a triangle');
writeln('after you enter their dimensions.');
writeln('When asked to, type in a dimension and hit the ENTER key.');
writeln;
{-------------------Inputting Data------------------}
{------User-Friendly------}
Repeat
write('What is the triangle''s base? ');
readln(b);
if b <= 0 then
writeln('The base needs to be GREATER than zero.')
Until b > 0;
{------VERY User-Friendly------}
Repeat
write('What is the triangle''s height? ');
readln(h_string);
val(h_string, h, Err);
if Err > 0 then
writeln('An illegal character was found at character #', Err, '.')
else if h <= 0 then
writeln('The height needs to be GREATER than zero.')
Until (h > 0) AND (Err = 0);
{-------------------Calculation------------------}
A := b * h / 2;
{-------------------Printing Results------------------}
writeln('The area of a triangle with a base of ', b:0, ' units and');
writeln('a height of ', h:0, ' units is ', A:0:1, ' square units.');
end.