Computers are excellent at doing the same operation over and over again. Sometimes the user runs a program by accident and would like to exit immediately, instead of running the task even once. When dealing with any user, it is best to provide him/her with as much control over the process as possible. This can be accomplished by using a beginning-exit loop, which allows the user, while s/he wants to, to repetitively do a task.
We will use another modification of the area-of-a-triangle program to illustrate this. The problem, pseudocode and flowchart are as follows:
The Problem: Write a program to calculate the areas of as many triangles as the user would like to have done, with the user providing the dimensions. Permit the user to exit without having any calculations done.
The Pseudocode:
1. Simple introduction and instructions;
2. Give user a chance to exit;
3. Do the main job repeatedly if asked to
a) Find out the dimensions;
b) Calculate the area;
c) Print out the results;
d) Ask whether to continue or not.
A beginning-exit loop contains the statements that are to be repeated. Indentation is used to help the programmer visualize the structure of the loop. A comment is frequently placed at the end of the loop so you know which loop the end loop terminates.
When using a beginning-exit loop, a variable is used to determine whether the loop should be executed or not. This is known as the "loop control variable" and is given the name KeepGoing in this program. It is tested/checked at the beginning of each iteration of the loop, as opposed to the end-exit loop, which checks the variable at the end. It is of type char, and when it has a value of n or N, the task is not done.
% beginning-exit loop var b, h: int %Base & Height var A: real %Area var KeepGoing: char %Loop control variable %------------Introduction & Setup------------------ put "This program calculates and prints the areas of triangles" put "one after another after you enter their dimensions." put "When asked to, type in a dimension and hit the ENTER key." %-------------------User Control------------------ put "Do you want to continue? (Y/N) ".. get KeepGoing put "" loop exit when (KeepGoing = 'N') or (KeepGoing = 'n') %-------------------Inputting Data------------------ put "What is the length of the triangle's base? ".. get b put "What is the triangle's height? ".. get 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." put "" %-------------------User Control------------------ put "Do you want to do another? (Y/N) ".. get KeepGoing end loop