Calculate the area of a circle and modify the same program to calculate the volume of a cylinder given its radius and height.
To calculate the area of a circle in C, you can use the formula A = π r r, where A is the area and r is the radius of the circle.
Here is an example code that calculates the area of a circle:
#include <stdio.h>
#define PI 3.14159
int main() {
float radius, area;
printf("Enter the radius of the circle: ");
scanf("%f", &radius);
area = PI radius radius;
printf("The area of the circle is: %.2f\n", area);
return 0;
}
In this code, we first include the <stdio.h>
header file, which contains the necessary functions for input and output. We also define the value of PI as 3.14159 using a preprocessor directive #define
.
Inside the main()
function, we declare two variables: radius
to store the radius entered by the user, and area
to store the calculated area.
We then prompt the user to enter the radius of the circle using printf()
, and read the value entered by the user using scanf()
and the %f
format specifier.
Next, we calculate the area of the circle using the formula A = PI radius radius
, and store the result in the area
variable.
Finally, we display the calculated area using printf()
with the format specifier %.2f
to display the result with two decimal places.
To calculate the volume of a cylinder, you can use the formula V = π r r * h, where V is the volume, r is the radius, and h is the height of the cylinder.
Here is an example code that calculates the volume of a cylinder based on the radius and height:
#include <stdio.h>
#define PI 3.14159
int main() {
float radius, height, volume;
printf("Enter the radius of the cylinder: ");
scanf("%f", &radius);
printf("Enter the height of the cylinder: ");
scanf("%f", &height);
volume = PI radius radius * height;
printf("The volume of the cylinder is: %.2f\n", volume);
return 0;
}
In this code, we declare three variables: radius
to store the radius entered by the user, height
to store the height entered by the user, and volume
to store the calculated volume.
We prompt the user to enter the radius and height of the cylinder using printf()
, and read the values entered by the user using scanf()
and the %f
format specifier.
We then calculate the volume of the cylinder using the formula V = PI radius radius * height
, and store the result in the volume
variable.
Finally, we display the calculated volume using printf()
with the format specifier %.2f
to display the result with two decimal places.