Compute Area = 0.5 _ Base _ Height
In this step, you will learn how to calculate the area of a triangle using the formula: Area = 0.5 _ Base _ Height. We'll modify the previous program to compute and display the triangle's area.
Open the existing file:
cd ~/project
nano triangle_area.c
Update the code to calculate the area:
#include <stdio.h>
int main() {
float base, height, area;
// Prompt user to enter base
printf("Enter the base of the triangle: ");
scanf("%f", &base);
// Prompt user to enter height
printf("Enter the height of the triangle: ");
scanf("%f", &height);
// Calculate area
area = 0.5 * base * height;
// Print input values and calculated area
printf("Base: %.2f\n", base);
printf("Height: %.2f\n", height);
printf("Area of the triangle: %.2f\n", area);
return 0;
}
Compile the updated program:
gcc triangle_area.c -o triangle_area
Example output:
(no output if compilation is successful)
Run the program:
./triangle_area
Example output:
Enter the base of the triangle: 5.5
Enter the height of the triangle: 4.2
Base: 5.50
Height: 4.20
Area of the triangle: 11.55
Let's break down the area calculation:
- We added a new
float
variable area
- The formula
area = 0.5 * base * height
calculates the triangle's area
printf()
displays the calculated area with two decimal places