Compute the Perimeter of a Polygon in C

CCBeginner
Practice Now

Introduction

In this lab, you will learn how to compute the perimeter of a polygon in C. The lab covers the following steps: reading side lengths into an array, summing all sides, and printing the perimeter. You will create a program that allows users to input the lengths of a polygon's sides, store them in an array, and then calculate the perimeter by adding up all the side lengths.

The lab provides a step-by-step guide, including sample code, to help you understand and implement the polygon perimeter calculation in C. By the end of the lab, you will have a working program that can compute the perimeter of a polygon with up to 10 sides.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL c(("`C`")) -.-> c/UserInteractionGroup(["`User Interaction`"]) c(("`C`")) -.-> c/BasicsGroup(["`Basics`"]) c(("`C`")) -.-> c/ControlFlowGroup(["`Control Flow`"]) c(("`C`")) -.-> c/CompoundTypesGroup(["`Compound Types`"]) c/UserInteractionGroup -.-> c/output("`Output`") c/BasicsGroup -.-> c/variables("`Variables`") c/ControlFlowGroup -.-> c/for_loop("`For Loop`") c/CompoundTypesGroup -.-> c/arrays("`Arrays`") c/UserInteractionGroup -.-> c/user_input("`User Input`") subgraph Lab Skills c/output -.-> lab-435164{{"`Compute the Perimeter of a Polygon in C`"}} c/variables -.-> lab-435164{{"`Compute the Perimeter of a Polygon in C`"}} c/for_loop -.-> lab-435164{{"`Compute the Perimeter of a Polygon in C`"}} c/arrays -.-> lab-435164{{"`Compute the Perimeter of a Polygon in C`"}} c/user_input -.-> lab-435164{{"`Compute the Perimeter of a Polygon in C`"}} end

Read Side Lengths into an Array

In this step, you'll learn how to read side lengths into an array for calculating a polygon's perimeter in C. We'll create a program that allows users to input the lengths of a polygon's sides and store them in an array.

First, let's create a C source file in the project directory:

cd ~/project
nano polygon_perimeter.c

Now, enter the following code:

#include <stdio.h>

#define MAX_SIDES 10

int main() {
    float sides[MAX_SIDES];
    int num_sides;

    // Prompt user for the number of sides
    printf("Enter the number of sides in the polygon (max %d): ", MAX_SIDES);
    scanf("%d", &num_sides);

    // Input side lengths
    printf("Enter the lengths of the sides:\n");
    for (int i = 0; i < num_sides; i++) {
        printf("Side %d length: ", i + 1);
        scanf("%f", &sides[i]);
    }

    // Print the input side lengths
    printf("\nSide lengths entered:\n");
    for (int i = 0; i < num_sides; i++) {
        printf("Side %d: %.2f\n", i + 1, sides[i]);
    }

    return 0;
}

Compile the program:

gcc -o polygon_perimeter polygon_perimeter.c

Run the program:

./polygon_perimeter

Example output:

Enter the number of sides in the polygon (max 10): 4
Enter the lengths of the sides:
Side 1 length: 5.5
Side 2 length: 6.2
Side 3 length: 4.3
Side 4 length: 7.1

Side lengths entered:
Side 1: 5.50
Side 2: 6.20
Side 3: 4.30
Side 4: 7.10

Let's break down the key parts of the code:

  • #define MAX_SIDES 10 sets a maximum limit for the number of sides
  • float sides[MAX_SIDES] creates an array to store side lengths
  • scanf() is used to read the number of sides and individual side lengths
  • A for loop is used to input and then display the side lengths

Sum All Sides

In this step, you'll modify the previous program to calculate the perimeter by summing all the side lengths of the polygon.

Open the existing file:

cd ~/project
nano polygon_perimeter.c

Update the code with the perimeter calculation:

#include <stdio.h>

#define MAX_SIDES 10

int main() {
    float sides[MAX_SIDES];
    int num_sides;
    float perimeter = 0.0;

    // Prompt user for the number of sides
    printf("Enter the number of sides in the polygon (max %d): ", MAX_SIDES);
    scanf("%d", &num_sides);

    // Input side lengths
    printf("Enter the lengths of the sides:\n");
    for (int i = 0; i < num_sides; i++) {
        printf("Side %d length: ", i + 1);
        scanf("%f", &sides[i]);
    }

    // Calculate perimeter by summing all sides
    for (int i = 0; i < num_sides; i++) {
        perimeter += sides[i];
    }

    // Print the side lengths and perimeter
    printf("\nSide lengths entered:\n");
    for (int i = 0; i < num_sides; i++) {
        printf("Side %d: %.2f\n", i + 1, sides[i]);
    }

    // Display the calculated perimeter
    printf("\nPerimeter of the polygon: %.2f\n", perimeter);

    return 0;
}

Compile the updated program:

gcc -o polygon_perimeter polygon_perimeter.c

Run the program:

./polygon_perimeter

Example output:

Enter the number of sides in the polygon (max 10): 4
Enter the lengths of the sides:
Side 1 length: 5.5
Side 2 length: 6.2
Side 3 length: 4.3
Side 4 length: 7.1

Side lengths entered:
Side 1: 5.50
Side 2: 6.20
Side 3: 4.30
Side 4: 7.10

Perimeter of the polygon: 23.10

Key changes in this step:

  • Added a perimeter variable to store the total sum of side lengths
  • Introduced a new for loop to calculate the perimeter by adding all sides
  • Added a print statement to display the calculated perimeter

Print the Perimeter

In this final step, you'll enhance the polygon perimeter calculation program by adding formatted output and error handling for input validation.

Open the existing file:

cd ~/project
nano polygon_perimeter.c

Update the code with improved input validation and formatted output:

#include <stdio.h>

#define MAX_SIDES 10
#define MIN_SIDES 3

int main() {
    float sides[MAX_SIDES];
    int num_sides;
    float perimeter = 0.0;

    // Prompt user for the number of sides with input validation
    do {
        printf("Enter the number of sides in the polygon (between %d and %d): ",
               MIN_SIDES, MAX_SIDES);
        scanf("%d", &num_sides);

        if (num_sides < MIN_SIDES || num_sides > MAX_SIDES) {
            printf("Invalid number of sides. Please try again.\n");
        }
    } while (num_sides < MIN_SIDES || num_sides > MAX_SIDES);

    // Input side lengths with validation
    printf("Enter the lengths of the sides:\n");
    for (int i = 0; i < num_sides; i++) {
        float side_length;
        do {
            printf("Side %d length (must be positive): ", i + 1);
            scanf("%f", &side_length);

            if (side_length <= 0) {
                printf("Invalid side length. Please enter a positive value.\n");
            } else {
                sides[i] = side_length;
                break;
            }
        } while (1);
    }

    // Calculate perimeter by summing all sides
    for (int i = 0; i < num_sides; i++) {
        perimeter += sides[i];
    }

    // Formatted output of results
    printf("\n--- Polygon Perimeter Calculation ---\n");
    printf("Number of Sides: %d\n", num_sides);

    printf("\nSide Lengths:\n");
    for (int i = 0; i < num_sides; i++) {
        printf("Side %d: %.2f\n", i + 1, sides[i]);
    }

    printf("\nPerimeter Calculation:\n");
    for (int i = 0; i < num_sides; i++) {
        printf("%s%.2f", (i > 0) ? " + " : "", sides[i]);
    }
    printf(" = %.2f\n", perimeter);

    printf("\nFinal Perimeter: %.2f\n", perimeter);

    return 0;
}

Compile the updated program:

gcc -o polygon_perimeter polygon_perimeter.c

Run the program:

./polygon_perimeter

Example output:

Enter the number of sides in the polygon (between 3 and 10): 4
Enter the lengths of the sides:
Side 1 length (must be positive): 5.5
Side 2 length (must be positive): 6.2
Side 3 length (must be positive): 4.3
Side 4 length (must be positive): 7.1

--- Polygon Perimeter Calculation ---
Number of Sides: 4

Side Lengths:
Side 1: 5.50
Side 2: 6.20
Side 3: 4.30
Side 4: 7.10

Perimeter Calculation:
5.50 + 6.20 + 4.30 + 7.10 = 23.10

Final Perimeter: 23.10

Key improvements in this step:

  • Added input validation for number of sides and side lengths
  • Created a more detailed and formatted output
  • Included a step-by-step perimeter calculation display
  • Ensured minimum and maximum side constraints

Summary

In this lab, you will learn how to read the side lengths of a polygon into an array, sum all the sides to compute the perimeter, and print the result. First, you will prompt the user to enter the number of sides and the length of each side, storing the side lengths in an array. Then, you will sum all the side lengths to calculate the perimeter of the polygon. Finally, you will print the computed perimeter.

The key steps include using scanf() to read user input, storing the side lengths in an array, iterating through the array to sum the side lengths, and printing the final result.

Other C Tutorials you may like