Print the Area
In this step, you will enhance the program to provide a more descriptive output of the rectangle's area calculation.
Open the existing C file:
cd ~/project
nano rectangle_area.c
Update the code to format the area output more professionally:
#include <stdio.h>
int main() {
float length, width, area;
// Prompt user to enter length
printf("Rectangle Area Calculator\n");
printf("------------------------\n");
printf("Enter the length of the rectangle: ");
scanf("%f", &length);
// Prompt user to enter width
printf("Enter the width of the rectangle: ");
scanf("%f", &width);
// Calculate the area
area = length * width;
// Print formatted area result
printf("\nCalculation Results:\n");
printf("Length: %.2f units\n", length);
printf("Width: %.2f units\n", width);
printf("Area: %.2f square units\n", area);
return 0;
}
Compile and run the updated program:
gcc rectangle_area.c -o rectangle_area
./rectangle_area
Example output:
Rectangle Area Calculator
------------------------
Enter the length of the rectangle: 6.0
Enter the width of the rectangle: 4.5
Calculation Results:
Length: 6.00 units
Width: 4.50 units
Area: 27.00 square units
Code Explanation:
- Added descriptive headers and formatting
- Included units in the output for clarity
- Improved readability of the calculation results
- Used
\n
for line breaks to create visual separation