A major advantage of using functions is to have code sections which are frequently used in a program placed in functions in order to shorten the overall length of the program.
As you may have already experienced, the user can not be relied upon to enter only appropriate data. If a program is trying to read in an integer and it receives a string instead, the input is ignored and the variable remains unchanged. This can, and most often does, cause unexpected results. Avoiding this kind of problem is known as bulletproofing.
The program below combines these two concepts and illustrates several new things:
However, there is frequently a cost involved with making a function reusable. It may have to be generalized, i.e., various parameters may have to be used to handle individual cases, e.g., whichvar.
#include <stdio.h> /* standard I/O header file */
/* function prototypes */
void Introduction();
void InputtingData(int *, int *);
void Calculation(int, int, float *);
void PrintingResults(int, int, float);
void GetPositiveInteger(int *, char *);
void main()
{
int base;
int height;
float Area;
Introduction();
InputtingData(&base, &height);
Calculation(base, height, &Area);
PrintingResults(base, height, Area);
}
void 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 RETURN key.\n");
printf("\n");
} /* Introduction */
void InputtingData(int *b, int *h)
{
printf("What is the length of the triangle's base? ");
GetPositiveInteger(b, "base");
printf("What is the triangle's height? ");
GetPositiveInteger(h, "height");
} /* InputtingData */
void Calculation(int b, int h, float *A)
{
*A = b * h / 2.0;
} /* Calculation */
void PrintingResults(int b, int h, float A)
{
printf("\n");
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);
} /* PrintingResults */
void GetPositiveInteger( int *newinteger, char *whichvar)
{
int badinputflag;
char dummystr[25];
do {
badinputflag = scanf("%d", newinteger);
if (badinputflag == 0)
{
scanf("%s", dummystr); /* Clear the input buffer */
printf("A typo was found for %s.\n", whichvar);
printf("Please re-enter a value for the %s: ", whichvar);
}
else if (*newinteger <= 0)
{
printf("The %s needs to be GREATER than zero.\n", whichvar);
printf("Please re-enter a value for the %s: ", whichvar);
}
} while ( (badinputflag == 0) || (*newinteger <= 0) );
} /* GetPositiveInteger */