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