As the problems you work on get larger, it becomes ever more important to break them down into smaller parts. The smaller parts should each deal with a small task. This technique has two important advantages:
A third advantage, which is not demonstrated here, 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.
These smaller chunks of code can be bounded by their own curly brackets and given names. Each named code segment is called a function.
All functions are placed at the end of the program after the function main(). The main line of the program is found at the beginning of the file after the declaration of global variables.
The program below, a reworking of the earlier area-of-a-triangle program, includes several new things:
#include <stdio.h> /* standard I/O header file */
/* function prototypes */
void Introduction();
void InputtingData();
void Calculation();
void PrintingResults();
/* GLOBAL VARIABLES */
int b; /* Base */
int h; /* Height */
float A; /* Area */
void main()
{
Introduction();
InputtingData();
Calculation();
PrintingResults();
}
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()
{
printf("What is the length of the triangle's base? ");
scanf("%d", &b);
printf("What is the triangle's height? ");
scanf("%d", &h);
} /* InputtingData */
void Calculation()
{
A = b * h / 2.0;
} /* Calculation */
void PrintingResults()
{
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 */
© DFStermole: 4 Oct 98
HTMLified: 4 Oct 98