Sunday, July 13, 2008

Area of a circle, given the radius

/* Write a C program to find the area of a circl, given the adius*/

#include stdio.h
#include conio.h
#include math.h
#define PI 3.142

void main()
{
float radius, area;
clrscr();

printf("Enter the radius of a circle\n");
scanf ("%f", &radius);

area = PI * pow (radius,2);

printf ("Area of a circle = %5.2f\n", area);
}

/*-----------------------------
Output

RUN1
Enter the radius of a circle
3.2
Area of a circle = 32.17

RUN 2
Enter the radius of a circle
6
Area of a circle = 113.11

------------------------------*/

This program calculates the area of the circle using the classical formula. This program seems straight forward but there are a couple of concepts highlighted here. The first one is the predefined value of PI in preprocessor statements. This declares the value of PI before only. So that it can be used as a keyword temporarily. This thye of constants are called symbolic constants


pow() is the predefined function in math header file. So we have declared it in predefined functions.


The third most imporatnat thing is %5.2f. This thpe of declaration is used for defining the data type of output. This allocates 5 vacant spaces for the whole output obtained from statement. The 2 allocates 2 places for the value after decimal. So only two values are displyed in the output. The 5 places being occupied are 3,2,.,1,7. The main reason of doing so is to stop the memory over flow. This not only saves the execution time but also reduces the memory spaces used. You can think that we can declare the same at starting. If we are doimg so, that memory is allocated form starting only which will be vacant till the program is executed. So its better we create it just before executing as it will save our resources.

No comments: