11 May 2012

Coding Functions in 'C'

In order to create and use a function in 'C', the programmer must provide three things which have matching descriptions:

  1. A function prototype - describes the structure of the function to the compiler.
  2. A function call - passes program control to the function.
  3. A function header - begins the program code of the function.
Function Prototype

A prototype shows the name of the function
and the type of data the function will process.
void DoAction(void);
indicates that the function returns no value and receives no data.

Function Call

The function call passes control to the function.
Passes control to the DoAction function.

Function Header

The function header defines the function. The body of the function code is defined by { }.
// Sample code for Triangle Calculator

void CalculateArea();    // Function Prototype

void main()
    printf("Triangle Area Calculator");
    CalculateArea(); // Function Call
    printf("Program Complete");

void CalculateArea()    // Function Header
    float Height, Base, Area;

    printf("Enter the Height ");
    scanf("%f%*c", &Height);
    printf("Enter the Base ");
    scanf("%f%*c", &Base);
    Area = Height * Base / 2.0;
    printf("The Area is %0.2f\n", Area);

No comments:

Post a Comment