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 end-exit 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. strintok() returns true if the conversion from string to int is ok to perform, and false if it is not.
% Getting Data in a VERY User-Friendly Way Using an end-exit Loop
var b, h: int %Base & Height
var h_string : string % Height read in as a string
var A: real %Area
%------------Introduction & Setup------------------
put "This program calculates and prints the area of a triangle"
put "after you enter its dimensions."
put "When asked to, type in a dimension and hit the ENTER key."
%-------------------Inputting Data------------------
%------User-Friendly------
loop
put "What is the length of the triangle's base? "..
get b
if b <= 0 then
put "The base needs to be GREATER than zero."
end if
exit when b > 0
end loop % Getting b
%------VERY User-Friendly------
loop
put "What is the triangle's height? "..
get h_string
if strintok(h_string) = false then
put "An illegal character was found."
else
h := strint(h_string)
if h <= 0 then
put "The height needs to be GREATER than zero."
end if
exit when h > 0
end if
end loop % Getting h
%-------------------Calculation------------------
A := b * h / 2
%-------------------Print the result---------------
put "The area of a triangle with a base of ", b, " units and"
put "a height of ", h, " units is ", A:0:1, " square units."