Print the Area
In this step, you will enhance the trapezoid area calculation program by adding formatted output and error handling to improve user experience.
Open the existing file and update the code:
cd ~/project
nano trapezoid_area.c
Replace the previous code with the following implementation:
#include <stdio.h>
int main() {
float side1, side2, height, area;
// Input validation
printf("Trapezoid Area Calculator\n");
printf("-------------------------\n");
// Prompt user to input first parallel side
printf("Enter the length of the first parallel side: ");
if (scanf("%f", &side1) != 1 || side1 <= 0) {
printf("Error: Invalid input for first side.\n");
return 1;
}
// Prompt user to input second parallel side
printf("Enter the length of the second parallel side: ");
if (scanf("%f", &side2) != 1 || side2 <= 0) {
printf("Error: Invalid input for second side.\n");
return 1;
}
// Prompt user to input height
printf("Enter the height of the trapezoid: ");
if (scanf("%f", &height) != 1 || height <= 0) {
printf("Error: Invalid input for height.\n");
return 1;
}
// Calculate area using trapezoid area formula
area = 0.5 * (side1 + side2) * height;
// Formatted output of results
printf("\nTrapezoid Calculation Results:\n");
printf("-----------------------------\n");
printf("First Side: %.2f\n", side1);
printf("Second Side: %.2f\n", side2);
printf("Height: %.2f\n", height);
printf("Area: %.2f square units\n", area);
return 0;
}
Compile and run the program:
gcc trapezoid_area.c -o trapezoid_area
./trapezoid_area
Example output:
Trapezoid Area Calculator
-------------------------
Enter the length of the first parallel side: 5
Enter the length of the second parallel side: 7
Enter the height of the trapezoid: 3
Trapezoid Calculation Results:
-----------------------------
First Side: 5.00
Second Side: 7.00
Height: 3.00
Area: 18.00 square units
Explanation
- Added input validation to prevent invalid inputs
- Improved output formatting with headers and clear labels
- Added error handling for incorrect input types
- Included descriptive output with all input parameters and calculated area
- Used
%.2f
to display floating-point numbers with two decimal places