Determine Triangle Type in C++
This C++ exercise focuses on conditional logic and input handling. The program asks the user to input the lengths of the three sides of a triangle and determines whether it is equilateral, isosceles, or scalene.
This activity enhances your understanding of nested conditionals, logical operators (&&, ||), and basic geometry principles applied in programming.
Triangle Definitions
Equilateral
All three sides are equal in length. (a == b && b == c)
Isosceles
At least two sides are equal in length. (a == b || a == c...)
Scalene
All three sides have different lengths. (a != b && b != c...)
The Triangle Inequality Theorem
Before classifying, the program must verify if a triangle is even possible. The sum of any two sides must be greater than the third side (e.g., a + b > c).
Objectives
- 1. Input three side lengths using
floatordouble. - 2. Implement the Triangle Inequality Theorem to validate the input.
- 3. Use nested
if-elsestructures to categorize the triangle. - 4. Output the specific type or an error message if the triangle is invalid.
Example C++ Code
#include <iostream>
using namespace std;
int main() {
float side1, side2, side3;
cout << "Enter side 1: "; cin >> side1;
cout << "Enter side 2: "; cin >> side2;
cout << "Enter side 3: "; cin >> side3;
// Validation: Triangle Inequality Theorem
if (side1 + side2 > side3 && side1 + side3 > side2 && side2 + side3 > side1) {
if (side1 == side2 && side2 == side3) {
cout << "Result: Equilateral triangle." << endl;
}
else if (side1 == side2 || side1 == side3 || side2 == side3) {
cout << "Result: Isosceles triangle." << endl;
}
else {
cout << "Result: Scalene triangle." << endl;
}
} else {
cout << "Error: Not a valid triangle." << endl;
}
return 0;
}
Console Output:
Enter side 2: 5
Enter side 3: 8
Result: Isosceles triangle.