Wednesday, April 30, 2025

C Program - Calculate Area and Circumference of a Circle

This program calculates the area and circumference of a circle based on a user inputted radius.

It first defines the constant value of PI as 3.14159.

Then, it prompts the user to input the radius of the circle using printf and reads in the user's input using scanf.

It calculates the area of the circle using the formula "PI * radius * radius" and stores it in the "area" variable. It also calculates the circumference of the circle using the formula "2 * PI * radius" and stores it in the "circumference" variable.

Finally, it prints the calculated values of the area and circumference to the console using printf, and returns 0 to indicate successful program execution. 

//are and circumference of a circle
#include <stdio.h>

#define PI 3.14159

int main()
{

    float area, circumference, radius;

    printf("Circle Radius: \n");
    scanf("%f", &radius);

    area = PI * radius * radius;
    printf("Area: %f \n", area);

    circumference = 2 * PI * radius;
    printf("Circumference: %f \n", circumference);

    return 0;

}

Result: 

Circle Radius:
20
Area: 1256.635986
Circumference: 125.663597

Process returned 0 (0x0)   execution time : 1.969 s
Press any key to continue.

Here's a line-by-line explanation of the code: 

#include <stdio.h>

This line includes the standard input/output library, which is needed for functions like printf and scanf. 

#define PI 3.14159

This line defines a constant value called "PI" and sets it equal to 3.14159. This constant will be used to calculate the area and circumference of the circle. 

int main()
{
    float area, circumference, radius;

    printf("Circle Radius: \n");
    scanf("%f", &radius);

This is the "main" function of the program. It declares three float variables: "area", "circumference", and "radius". It then uses printf to ask the user to input the radius of the circle, and uses scanf to read in the user's input and store it in the "radius" variable. 

    area = PI * radius * radius;
    printf("Area: %f \n", area);

This calculates the area of the circle using the formula "PI * radius * radius" and stores it in the "area" variable. It then uses printf to print the calculated area to the console. 

    circumference = 2 * PI * radius;
    printf("Circumference: %f \n", circumference);

This calculates the circumference of the circle using the formula "2 * PI * radius" and stores it in the "circumference" variable. It then uses printf to print the calculated circumference to the console. 

    return 0;
}

Finally, the main function returns 0 to indicate successful program execution.

No comments:

Post a Comment

Tkinter Introduction - Top Widget, Method, Button

First, let's make shure that our tkinter module is working ok with simple  for loop that will spawn 5 instances of blank Tk window .  ...