If lengths of three sides of a Triangle are input through the keyboard, write a program to find the area of the Triangle.
Related Read:
Basic Arithmetic Operations In C
Triangle Valid or Not based On Sides: C Program
Note:A Triangle is valid if the sum of 2 sides of the Triangle is greater than the largest of the 3 sides.
Important: In this program we assume that the user has entered valid lengths of the Triangle.
sp = (a + b + c) / 2.0;
area = sqrt( sp * (sp-a) * (sp-b) * (sp-c) );
where a, b and c are lengths of sides of the Triangle.
sp – Semi-perimeter.
Note: In geometry, above formula to calculate area of Triangle is called Heron’s formula (sometimes called Hero’s formula).
Find Area of a Triangle Using Its Sides: C Program
#include < stdio.h > #include < math.h > int main() { float a, b, c, sp, area; printf("Enter values of a, b and c\n"); scanf("%f%f%f", &a, &b, &c); sp = (a+b+c)/2.0; area = sqrt(sp*(sp-a)*(sp-b)*(sp-c)); printf("Area of triangle is %f\n", area); return 0; }
Output:
Enter values of a, b and c
4
5
6
Area of triangle is 9.921567
Note: While calculating Semi-perimeter, make sure to divide by 2.0 and not by 2. Because division by integer number returns only the integer part of the result. So for certain inputs the result might be wrong. So always use the floating/double value while dividing in C Programs.
Note: Since we are using sqrt() method, we need to include math.h library file (header file) without fail.
For list of all c programming interviews / viva question and answers visit: C Programming Interview / Viva Q&A List
For full C programming language free video tutorial list visit:C Programming: Beginner To Advance To Expert