Functions

How functions work

  1. A function is called by name, sometimes is passed arguments, performs a certain duty, and returns a value.
  2. printf and scanf are library functions, meaning they have already been defined by someone else
  3. The functions discussed here are user functions; they are defined by you!

An example program

  1. The following example program has a function called TriArea that calculates the area of a triangle (1/2 * base * height).
    Example:
    #include <stdio.h>
    
    double TriArea(double, double);
    
    int main() {
    
        double base, height, area;
    
        printf("Enter the length of the base of your triangle >>");
    
        scanf("%lf", &base);
    
        printf("\nEnter the height of your triangle >>");
    
        scanf("%lf", &height);
    
        area = TriArea(base,height);
    
        printf("\nThe area is %f", area);
    
        return 0;
    
    }
    
    double TriArea(double b1, double h1) {
    
        double a1;
    
        a1 = .5 * b1 * h1;
    
        return a1;
    
    }
        
    
    
    Source File | DOS Executable (run from DOS prompt)

  2. The first time that the function's name appears in the above code is the function prototype. This is used to let the compiler know that there will be a function named TriArea, even though it has not been defined yet.
  3. In the prototype, you declare the function to be a certain type, just like you do with variables. However, the type "void" applies to functions only. A void function returns no value. In the example, the type is "double," so the function must return a double number.