Back to DFS's C Page


FUNCTIONS I
Basics of Functions

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:

  1. Each piece is easier to program -- you won't be overwhelmed by the larger problem;
  2. It will be easier to ferret out mistakes, i.e., to find the bugs.

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:

  1. Each of the four labelled sections of the earlier version now appears in its own function;
  2. Comments indicate where each function ends -- this may not seem important now with these short functions, but using this technique will make your later, larger functions and programs more readable;
  3. The calls to the various functions all appear in the main() function, although in more complicated programs this will not be the case.
  4. The function prototypes appear at the beginning of the file to give the compiler information for checking program logic.
  5. Global variables are declared before any of the functions are defined, making them accessible to all functions. This is not the best way to handle these variables. A better way is demonstrated in Functions II.
#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