Circle Area and Circumference in C

CCBeginner
Practice Now

Introduction

In this lab, we will create a C program that calculates the area and circumference of a circle. This simple program demonstrates several fundamental programming concepts including variable declaration, user input processing, mathematical calculations, and formatted output display.

Circle Area and Circumference in C

We will use the mathematical formulas:

  • Area of a circle = π × radius²
  • Circumference of a circle = 2 × π × radius

By the end of this lab, you will have written a complete C program that takes user input and performs calculations using these formulas.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL c(("C")) -.-> c/BasicsGroup(["Basics"]) c(("C")) -.-> c/FileHandlingGroup(["File Handling"]) c(("C")) -.-> c/UserInteractionGroup(["User Interaction"]) c/BasicsGroup -.-> c/variables("Variables") c/BasicsGroup -.-> c/data_types("Data Types") c/BasicsGroup -.-> c/constants("Constants") c/BasicsGroup -.-> c/operators("Operators") c/FileHandlingGroup -.-> c/create_files("Create Files") c/UserInteractionGroup -.-> c/user_input("User Input") c/UserInteractionGroup -.-> c/output("Output") subgraph Lab Skills c/variables -.-> lab-123197{{"Circle Area and Circumference in C"}} c/data_types -.-> lab-123197{{"Circle Area and Circumference in C"}} c/constants -.-> lab-123197{{"Circle Area and Circumference in C"}} c/operators -.-> lab-123197{{"Circle Area and Circumference in C"}} c/create_files -.-> lab-123197{{"Circle Area and Circumference in C"}} c/user_input -.-> lab-123197{{"Circle Area and Circumference in C"}} c/output -.-> lab-123197{{"Circle Area and Circumference in C"}} end

Creating the Program File and Basic Structure

Let's start by creating our C program file and setting up the basic structure. We'll create a file called circle.c in the ~/project/circle_program directory.

  1. Navigate to the project directory:

    cd ~/project/circle_program
  2. Create a new file named circle.c using the WebIDE editor. Click on the "File" menu at the top of the WebIDE, then select "New File". Alternatively, you can right-click in the file explorer panel and select "New File".

  3. Name the file circle.c and save it in the ~/project/circle_program directory.

  4. Now, let's add the basic structure of our C program to the file:

    #include <stdio.h>
    
    int main() {
        // We will add our code here
    
        return 0;
    }

In the above code:

  • #include <stdio.h> is a preprocessor directive that tells the compiler to include the Standard Input/Output library, which provides functions like printf() and scanf().
  • int main() defines the main function, which is the entry point of any C program.
  • The curly braces { } mark the beginning and end of the main function's body.
  • return 0; indicates that the program executed successfully.
  1. Save the file by pressing Ctrl+S or by using the "File" menu and selecting "Save".

Declaring Variables and Constants

Now that we have our basic program structure, let's add the variables and constants we'll need for our calculations.

  1. Open your circle.c file in the editor (if it's not already open).

  2. We'll need several variables:

    • A variable to store the radius of the circle
    • A constant to store the value of π (pi)
    • Variables to store the calculated area and circumference
  3. Update your code as follows:

    #include <stdio.h>
    
    int main() {
        // Declare variables and constants
        float radius;         // to store the radius of the circle
        const float PI = 3.14159; // the mathematical constant π (pi)
        float area;           // to store the calculated area
        float circumference;  // to store the calculated circumference
    
        return 0;
    }

Let's understand the variable declarations:

  • float radius; - We use the float data type because the radius could be a decimal number.
  • const float PI = 3.14159; - We define PI as a constant because its value should not change during program execution. The const keyword ensures this.
  • float area; and float circumference; - These variables will store our calculation results, which might be decimal numbers.

In C programming, we typically declare all variables at the beginning of a function. This practice makes the program more organized and easier to understand.

  1. Save your file (Ctrl+S).

Getting User Input

Now, let's add code to ask the user for the radius of the circle and read their input.

  1. Open your circle.c file in the editor (if it's not already open).

  2. Add the code to prompt the user and read their input:

    #include <stdio.h>
    
    int main() {
        // Declare variables and constants
        float radius;         // to store the radius of the circle
        const float PI = 3.14159; // the mathematical constant π (pi)
        float area;           // to store the calculated area
        float circumference;  // to store the calculated circumference
    
        // Prompt user for radius
        printf("Please enter the radius of the circle: ");
    
        // Read the radius value from user input
        scanf("%f", &radius);
    
        // Validate input (optional but good practice)
        if (radius <= 0) {
            printf("Error: Radius must be a positive number\n");
            return 1;  // Exit with error code
        }
    
        return 0;
    }

Let's understand what we added:

  • printf("Please enter the radius of the circle: "); - This displays a message asking the user to input the radius.
  • scanf("%f", &radius); - This reads a floating-point value from the user and stores it in the radius variable.
    • %f is a format specifier for floating-point numbers.
    • &radius passes the memory address of the radius variable, allowing scanf() to modify its value.
  • We added a simple validation check to ensure the radius is positive, as a circle cannot have a zero or negative radius.

The scanf() function is used to read formatted input from the standard input (keyboard). It's important to use the correct format specifier (%f for float) and to pass the address of the variable using the & operator.

  1. Save your file (Ctrl+S).

Calculating Area and Circumference

Now that we have the radius, we can calculate the area and circumference of the circle using our formulas.

  1. Open your circle.c file in the editor (if it's not already open).

  2. Add the calculation code:

    #include <stdio.h>
    
    int main() {
        // Declare variables and constants
        float radius;         // to store the radius of the circle
        const float PI = 3.14159; // the mathematical constant π (pi)
        float area;           // to store the calculated area
        float circumference;  // to store the calculated circumference
    
        // Prompt user for radius
        printf("Please enter the radius of the circle: ");
    
        // Read the radius value from user input
        scanf("%f", &radius);
    
        // Validate input
        if (radius <= 0) {
            printf("Error: Radius must be a positive number\n");
            return 1;  // Exit with error code
        }
    
        // Calculate the area of the circle
        area = PI * radius * radius;
    
        // Calculate the circumference of the circle
        circumference = 2 * PI * radius;
    
        return 0;
    }

Let's understand the calculations:

  • area = PI * radius * radius; - This calculates the area using the formula π × r², where r is the radius.
  • circumference = 2 * PI * radius; - This calculates the circumference using the formula 2 × π × r.

In C, the multiplication operator is *. To calculate r², we simply multiply the radius by itself (radius * radius). For more complex mathematical operations, we would use functions from the math.h library, but our calculations are simple enough without it.

  1. Save your file (Ctrl+S).

Displaying Results and Testing the Program

Let's complete our program by adding code to display the results, then compile and run it to see if it works correctly.

  1. Open your circle.c file in the editor (if it's not already open).

  2. Add the code to display the results:

    #include <stdio.h>
    
    int main() {
        // Declare variables and constants
        float radius;         // to store the radius of the circle
        const float PI = 3.14159; // the mathematical constant π (pi)
        float area;           // to store the calculated area
        float circumference;  // to store the calculated circumference
    
        // Prompt user for radius
        printf("Please enter the radius of the circle: ");
    
        // Read the radius value from user input
        scanf("%f", &radius);
    
        // Validate input
        if (radius <= 0) {
            printf("Error: Radius must be a positive number\n");
            return 1;  // Exit with error code
        }
    
        // Calculate the area of the circle
        area = PI * radius * radius;
    
        // Calculate the circumference of the circle
        circumference = 2 * PI * radius;
    
        // Display the results
        printf("\nResults for a circle with radius %.2f units:\n", radius);
        printf("Area: %.2f square units\n", area);
        printf("Circumference: %.2f units\n", circumference);
    
        return 0;
    }

Let's understand the output code:

  • printf("\nResults for a circle with radius %.2f units:\n", radius); - This displays the radius with 2 decimal places.
  • printf("Area: %.2f square units\n", area); - This displays the calculated area with 2 decimal places.
  • printf("Circumference: %.2f units\n", circumference); - This displays the calculated circumference with 2 decimal places.

The %.2f format specifier tells printf() to display floating-point numbers with 2 decimal places, making the output more readable.

  1. Save your file (Ctrl+S).

  2. Now, let's compile the program. In the terminal, navigate to your project directory and use the gcc compiler:

    cd ~/project/circle_program
    gcc circle.c -o circle

    The -o circle option tells the compiler to create an executable file named circle.

  3. If the compilation is successful, you can run your program with:

    ./circle
  4. When prompted, enter a radius value (for example, 5) and press Enter. You should see output similar to:

    Please enter the radius of the circle: 5
    
    Results for a circle with radius 5.00 units:
    Area: 78.54 square units
    Circumference: 31.42 units
  5. Try running the program again with different radius values to confirm it works correctly.

Congratulations! You have successfully created a C program that calculates and displays the area and circumference of a circle based on user input.

Summary

In this lab, you have successfully created a C program that:

  1. Prompts the user to enter the radius of a circle
  2. Reads and validates the user's input
  3. Calculates the area of the circle using the formula π × r²
  4. Calculates the circumference of the circle using the formula 2 × π × r
  5. Displays the calculated results with proper formatting

Along the way, you learned several important C programming concepts:

  • Including header files with #include
  • Defining and using variables and constants
  • Reading user input with scanf()
  • Performing mathematical calculations
  • Displaying formatted output with printf()
  • Compiling and running a C program

These fundamental skills form the building blocks for more complex C programs. You can now expand on this knowledge to create more sophisticated applications that involve user interaction and mathematical calculations.