Computers are excellent at doing the same operation over and over again. We can also get the computer to wait around until the user supplies a satisfactory value. This is an ideal situation for using a Do-While 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, pseudocode and flowchart 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 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. If the value given for the base is unsatisfactory, we simply request another. However, the loop for obtaining the value for the height internally checks to see if the value is not acceptable. If so, it lets the user know before prompting for another value. The latter technique is preferred because it is more user-friendly -- it not only tells the user that something is awry, the extra line of output also gives the user a visual cue that something is amiss.
#include <stdio.h> /* standard I/O header file */
void main()
{
int b, h; /* base, height */
float A; /* Area */
/* -------------------Introduction------------------ */
printf("This program calculates and prints the area of a triangle\n");
printf("after you enter its dimensions.\n");
printf("When asked to, type in a dimension and hit the ENTER key.\n");
printf("\n");
/* -------------------Inputting Data------------------*/
/*------NOT User-Friendly------*/
do {
printf("What is the length of the triangle's base? ");
scanf("%d", &b);
} while (b <= 0);
/*------User-Friendly------*/
do {
printf("What is the triangle's height? ");
scanf("%d", &h);
if (h <= 0)
printf("The height needs to be GREATER than zero.\n");
} while (h <= 0);
/* -------------------Calculation------------------ */
A = b * h / 2.0;
/* -------------------Printing Results------------------ */
printf("The area of a triangle with a base of %d units and\n", b);
printf("a height of %d units is %.1f square units.\n", h, A);
}