Login with username, password and session length
Resend Activation Email | Forgot your Password?
Join IT Acumens Discussion Zone Free!
Share this topic on FacebookShare this topic on MySpaceShare this topic on Del.icio.usShare this topic on DiggShare this topic on RedditShare this topic on StumbleUponShare this topic on TwitterShare this topic on TechnoratiShare this topic on MagnoliaShare this topic on GoogleShare this topic on Yahoo

Author [EN] [PL] [ES] [PT] [IT] [DE] [FR] [NL] [TR] [SR] [AR] [RU] Topic: Weight Conversion Table Using a Function  (Read 295 times)

Offline jayanthi mandhalapu

  • Acumen
  • Hero Member
  • ***
  • Posts: 4985
  • Acumen
    • View Profile
Weight Conversion Table Using a Function
« on: July 27, 2009, 08:19:05 AM »
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.
Be Happy And Always Remain So

IT Acumens Discussion Zone

« on: »