Lets ask the user to input lengths of 3 sides of the Triangle. First lets check if those 3 values form a valid Triangle. If it does, then we shall calculate perimeter, semi-perimeter and area of the Triangle. If it doesn’t form a valid Triangle, then we display that message on to the console window.
Related Read:
Find Area of a Triangle Using Its Sides: C Program
Logic To check if it’s a valid Triangle or Not
Logic to find if the user entered values for sides of Triangle actually forms a valid Triangle or not is present in our previous video tutorial. Please watch it without fail before continuing this tutorial. We’ve posted source code, video and explanation at Triangle Valid or Not based On Sides: C Program
Formula To Calculate Perimeter, Semi-perimeter and Area of a Triangle
p = (a + b + c);
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.
p – perimeter
sp – Semi-perimeter.
C Program To Find Area, Perimeter and Semi-perimeter: Valid Triangle
[youtube https://www.youtube.com/watch?v=CmGb-nlSC7o]
C Program To Find Area, Perimeter and Semi-perimeter: Valid Triangle
#include < stdio.h > #include < math.h > int main() { float a, b, c, flag = 0, p, sp, area; printf("Enter values for a, b and c\n"); scanf("%f%f%f", &a, &b, &c); if( a>b && a>c) { flag = ((b+c) > a); } else if( b>c ) { flag = ((a+c) > b); } else { flag = ((a+b) > c); printf("%f\n", flag); } if(flag) { p = a + b + c; sp = p / 2.0; area = sqrt( sp*(sp-a)*(sp-b)*(sp-c) ); printf("Perimeter is %f\n", p); printf("Semi-Perimeter is %f\n", sp); printf("Area of Triangle is %f\n", area); } else { printf("Invalid Triangle\n"); } return 0; }
Output 1:
Enter values for a, b and c
10
5
3
Invalid Triangle
Output 2:
Enter values for a, b and c
5
6
9
Perimeter is 20.000000
Semi-Perimeter is 10.000000
Area of Triangle is 14.142136
In above source code, variable flag stores true(1) or false(0) value.
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