How to Calculate the Area of a Circle in C (with Example Code)

Calculate the Area of a Circle in C

In this tutorial, we’ll develop a simple C program that calculates the area of a circle. The formula for the area of a circle is:

area = π × r × r

Program Code

#include <stdio.h>

int main() {
    float radius, area;
    const float PI = 3.14159265;

    // Prompt the user to enter the radius
    printf("Enter the radius of the circle: ");
    scanf("%f", &radius);

    // Calculate the area
    area = PI * radius * radius;

    // Display the result
    printf("The area of the circle with radius %.2f is %.2f\n", radius, area);

    return 0;
}

How the Program Works

  • We include the standard I/O library: <stdio.h>.
  • We declare two float variables: radius and area.
  • We define a constant PI for the value of π (3.14159265).
  • The user is prompted to enter the radius of the circle.
  • We use the scanf() function to read the user’s input.
  • We calculate the area using the formula area = π × r × r.
  • Finally, the program displays the calculated area using printf() with two decimal precision.

Output

Here’s what the output might look like:

Enter the radius of the circle: 5
The area of the circle with radius 5.00 is 78.54

Conclusion

This simple C program demonstrates how to use basic I/O and arithmetic operations to calculate the area of a circle. You can expand upon this by adding error checking for invalid radius values or by using mathematical libraries for more precision.

একটি মন্তব্য পোস্ট করুন