The program computes the area of triangle once he user enters input values for the triangle. The inputs for the triangle are the length of base and height of the triangle.
We compiled this program using Dev-C++ compiler installed on Windows 7 PC. You can use any standard C compiler if you like, but make sure to change the source code according to your compiler specifications. To get an error-free program is the goal.
You must be familiar with following C programming concepts before learning from the example. If you are familiar with them already, continue with the example program.
Problem Definition
This program needs two critical information about a triangle -length of base and the height of the triangle. The base of the triangle is the longer side and one endpoint of the height divides the base. See the figure below.
Now, the formula to find the area is as follows.
\begin{aligned} & Area = 1/2 \cdot (Base) \cdot (Height) \\\\ &Area = 1/2 \cdot b \cdot h\end{aligned}
Flowchart- Area of a Triangle
Program Code
/* Area of Triangle */
#include < stdio.h >
#include < stdlib.h >
main()
{
float base, height, area, i;
printf("Enter Base of the Triangle:");
scanf("%f", & base);
printf("Enter Height of the Triangle:");
scanf("%f",& height);
area = (base / 2) * height;
for (i = 0; i < 35; i++)
printf("_"); printf("\n\n");
printf("Area of Triangle: %f\n", area);
for (i = 0; i < 35; i++)
printf("_"); printf("\n\n");
system("PAUSE");
return 0;
}
Output
The output of the above program is given below. When you enter the required input values – Base and Height of the triangle. The program computes the area and display it on the console.
Enter Base of the Triangle:20
Enter Height of the Triangle:12
_____________________________________
Area of Triangle: 120.000000
_____________________________________