Recalling the concept of a triangle in geometry! A two-dimensional plane figure with three non-collinear points and three line segments connecting the vertices to form three sides of a triangle. A simple polygon, a convex polygon with 3 sides is called a triangle.
Calculate the perimeter and area of a triangle using C
Step 1: Start by entering the values of the three sides, a, b, and c, to check if they form a triangle.
Step 2: To calculate the perimeter of a triangle, simply add the lengths of its three sides. In other words: P = a + b + c
Step 3: The function perimeter(float a, float b, float c) returns a float (since the input sides are float values) and takes three parameters: a, b, and c, corresponding to the triangle's three sides.
You can refer to the C code below for calculating the perimeter:
#include
using std::cout;
float calculatePerimeter(int a, int b, int c) {
return a + b + c;
}
int main(){
float sideA, sideB, sideC;
cout < 'Enter side A:''>
cin >> sideA;
cout < 'Enter side B:''>
cin >> sideB;
cout < 'Enter side C:''>
cin >> sideC;
if (sideA >= sideB + sideC || sideB >= sideA + sideC || sideC >= sideA + sideB)
cout < 'The entered values do not form a valid triangle.''>
else {
cout < 'The perimeter of the triangle is: ' <<
}
system('pause');
return 0;
}
2. Calculating the Area of a Triangle in C
Step 1: After verifying that the sides a, b, c form a triangle -> the next step is to calculate the area using the Heron's formula.
Heron's formula is:
Where p is half of the triangle's perimeter, and S is the area of the triangle.
Step 2: The function calculateArea(float a, float b, float c) returns a float.
Step 3: You proceed to write a C program to calculate the area of the triangle.
#include
using namespace std;
float calculatePerimeter(int a, int b, int c) {
return a + b + c;
}
float calculateArea(int a, int b, int c) {
float p = calculatePerimeter(a, b, c) / 2.0;
return sqrt(p*(p - a)*(p - b)*(p - c));
}
int main(){
float sideA, sideB, sideC;
cout < 'Enter side A:''>
cin >> sideA;
cout < 'Enter side B:''>
cin >> sideB;
cout < 'Enter side C:''>
cin >> sideC;
if (sideA >= sideB + sideC || sideB >= sideA + sideC || sideC >= sideA + sideB)
cout < 'The entered values do not form a valid triangle.''>
else {
cout < 'The perimeter of the triangle is: ' <<
cout < 'The area of the triangle is: ' <<
}
system('pause');
return 0;
}
Finally, execute the program to get the results of the triangle's perimeter and area:
This concludes the article on C Exercise: Calculate Triangle Perimeter and Area using the C programming language. This is a fundamental problem that requires knowledge of geometry to calculate the triangle area using the Heron's formula. For the triangle perimeter, simply add the sides together. Additionally, it's advisable to check the validity of the triangle's side lengths before calculating the perimeter and area. Best of luck!