Q-3.Write a C program to input radius of a circle from user and find diameter, circumference and area of the circle. How to calculate diameter, circumference and area of a circle whose radius is given by user in C programming. Logic to find diameter, circumference and area of a circle in C.

0
/**
 * C program to calculate diameter, circumference and area of circle
 */

#include <stdio.h>

int main()
{
    float radius, diameter, circumference, area;
    
    /*
     * Input radius of circle from user
     */
    printf("Enter radius of circle: ");
    scanf("%f", &radius);

    /*
     * Calculate diameter, circumference and area
     */
    diameter = 2 * radius;
    circumference = 2 * 3.14 * radius;
    area = 3.14 * (radius * radius);

    /*
     * Print all results
     */
    printf("Diameter of circle = %.2f units \n", diameter);
    printf("Circumference of circle = %.2f units \n", circumference);
    printf("Area of circle = %.2f sq. units ", area);

    return 0;
}
\n is an escape sequence character used to add new line (move to next line).
Important note: The above program contains a constant value 3.14. It is always recommended to use constant variable to represent such constants. The constant PI is already defined in math.h header file with name M_PI.
Let us rewrite the above program using constant value.

Program to find diameter, circumference and area of circle using PI constant

/**
 * C program to calculate diameter, circumference and area of circle
 */

#include <stdio.h>
#include <math.h> // Used for M_PI

int main()
{
    float radius, diameter, circumference, area;
    
    /*
     * Input radius of circle from user
     */
    printf("Enter radius of circle: ");
    scanf("%f", &radius);

    /*
     * Calculate diameter, circumference and area of circle
     */
    diameter = 2 * radius;
    circumference = 2 * M_PI * radius;
    area = M_PI * (radius * radius);

    /*
     * Print all results
     */
    printf("Diameter of circle = %.2f units \n", diameter);
    printf("Circumference of circle = %.2f units \n", circumference);
    printf("Area of circle = %.2f sq. units ", area);

    return 0;
}

Post a Comment

0Comments
Post a Comment (0)