Group
Advanced Conditional Structures in C++
Objective
1. Prompt the user to enter the lengths of three sides of a triangle.
2. Use conditional statements to compare the sides.
3. Print whether the triangle is equilateral, isosceles, or scalene.
Develop a program that determines the type of triangle (equilateral, isosceles, scalene).
Example C++ Exercise
Show C++ Code
#include <iostream> // Include input/output library
using namespace std;
int main() {
// Declare variables to store the three side lengths
float side1, side2, side3;
// Ask the user to input the lengths of the three sides
cout << "Enter the length of side 1: ";
cin >> side1;
cout << "Enter the length of side 2: ";
cin >> side2;
cout << "Enter the length of side 3: ";
cin >> side3;
// Check if the inputs can form a valid triangle using triangle inequality
if (side1 + side2 > side3 && side1 + side3 > side2 && side2 + side3 > side1) {
// If all three sides are equal, it is an equilateral triangle
if (side1 == side2 && side2 == side3) {
cout << "The triangle is equilateral." << endl;
}
// If two sides are equal, it is an isosceles triangle
else if (side1 == side2 || side1 == side3 || side2 == side3) {
cout << "The triangle is isosceles." << endl;
}
// If all sides are different, it is a scalene triangle
else {
cout << "The triangle is scalene." << endl;
}
} else {
// If triangle inequality is not satisfied, it is not a valid triangle
cout << "The entered lengths do not form a valid triangle." << endl;
}
return 0; // End of program
}
Output
Enter the length of side 1: 5
Enter the length of side 2: 5
Enter the length of side 3: 5
The triangle is equilateral.