Next: Weight Conversion with Up: A Quick Overview Previous: A Weight Conversion

Weight Conversion Table Using a Function

The previous program could be better structured by defining a function to convert the weights and print out their values. It will then look like this.


#include <stdio.h>

void print_converted(int pounds)
/* Convert U.S. Weight to Imperial and International
   Units. Print the results */
{       int stones = pounds / 14;
        int uklbs = pounds % 14;
        float kilos_per_pound = 0.45359;
        float kilos = pounds * kilos_per_pound;

        printf("   %3d          %2d  %2d        %6.2f\n",
                pounds, stones, uklbs, kilos);
}

main()
{       int us_pounds;

        printf(" US lbs      UK st. lbs       INT Kg\n");

        for(us_pounds=10; us_pounds < 250; us_pounds+=10)
                print_converted(us_pounds);
}

void print_converted(int pounds) is the beginning of the function definition. The line within the loop reading print_converted(us_pounds) is a call to that function. When execution of the main function reaches that call, print_converted is executed, after which control returns to main.

The text enclosed by symbols /* and */ is a comment. These are C's way of separating plain text comments from the body of the program. It is usually good practice to have a short comment to explain the purpose of each function.

Defining a function has made this program larger, but what have we gained? The structure has been improved. This may make little difference to the readability of such a small program. In a larger program, such structuring makes the program shorter, easier to read, and simplifies future maintenance of the program. Another benefit of defining a function, is that the function can easily be re-used as part of another program.


January 1995