Complementary task for topic: 2

M Nemeth · 2023-08-29 15:21:04.606222'

If/else III.

If/else III.

Task: Determine the type of a triangle:
Write a C program that prompts the user to enter the lengths of three sides of a triangle and determines its type (equilateral, isosceles (two sides with the same length), scalene (no two sides with the same length, or not a triangle) using if/else statements. Display the result using printf().

Hint: Try to cover every possibility (how to get 2 sides to chaeck out of 3? there are 3 possibilities)

Solution
#include 

int main() {
    float side1, side2, side3;
    
    printf("Enter the length of side 1: ");
    scanf("%f", &side1);
    
    printf("Enter the length of side 2: ");
    scanf("%f", &side2);
    
    printf("Enter the length of side 3: ");
    scanf("%f", &side3);
    
    if (side1 == side2 && side2 == side3) {
        printf("The triangle is equilateral.\n");
    } else if (side1 == side2 || side1 == side3 || side2 == side3) {
        printf("The triangle is isosceles.\n");
    } else if (side1 + side2 > side3 && side1 + side3 > side2 && side2 + side3 > side1) {
        printf("The triangle is scalene.\n");
    } else {
        printf("The triangle is not a triangle.\n");
    }
    
    return 0;
}



Explanation
In this example, the program uses printf() to prompt the user to enter the lengths of three sides of a triangle. The scanf() function is used to scan the input from the user and store it in the variables side1, side2, and side3. The program uses if/else statements to check the conditions for different types of triangles. If all sides are equal, it is an equilateral triangle. If at least two sides are equal, it is an isosceles triangle. If none of the sides are equal and the sum of any two sides is greater than the third side, it is a scalene triangle. Otherwise, it is not a triangle.
< < previous    next > >