by Dinesh Thakur Category: Function and Pointer

Let us write a program to calculate the area' and circumference of a circle using user-defined functions. A function area_circum to accept the radius of a circle and print its area and circumference is given in Example. However, rather than printing the results in a function, it is good practice to return the results to the calling function, where they can be printed or used for further processing, if required. Hence, let us return the results (area and circumference) to the calling function.

As a function can return only one value through its name, we will require two functions in this program to calculate the area and circumference: area and circum. The program given below first defines the main function followed by these functions. The declarations of area and circum are given before the main function. Also, PI is defined as a global constant as it is required in both functions.

Note that we can change the order of definitions of area and circum. If we do so, we can also Change the sequence of their declarations, though it is not necessary. Note that we can also use a bottom-up approach and first define the functions area and circum in any order followed by the main function. As we know, this approach does not require declarations of area and circum.

/* Calculate area and circumference of a circle using functions */

#include <stdio.h>

const float PI = 3.1415927;

float area(float radius);

float circum(float radius);

void main()

{

      float radius;

      clrscr();

      printf("Enter radius: ");

      scanf("%f", &radius);

      printf("Area : %.3f\n", area(radius));

      printf("Circumference: %.3f\n", circum(radius));

      getch();

}

     /* return area of a circle */

     float area(float radius)

       {

             return PI * radius * radius;

       }

    /* return circumference of a circle */

    float circum(float radius)

       {

          return 2 * PI * radius;

       }

       C Program Calculate area and circumference of a circle using functions



About Dinesh Thakur

Dinesh ThakurDinesh Thakur holds an B.SC (Computer Science), MCSE, MCDBA, CCNA, CCNP, A+, SCJP certifications. Dinesh authors the hugely popular blog. Where he writes how-to guides around Computer fundamental , computer software, Computer programming, and web apps. For any type of query or something that you think is missing, please feel free to Contact us.



Related Articles