Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sequence of if-else if in C

Tags:

c

turbo-c

I' using the following logic for testing whether the triangle is isosceles, equilateral, scalene or right angled.

if (side1 == side2 || side2 == side3 || side1 == side3)
    printf("Isosceles triangle.");
else if (side1 == side2 && side2 == side3 && side3 == side1)
    printf("equilateral triangle");

I get the output for sides 3 3 3 as isosceles but not equilateral but when I interchange the logic that is write the logic of equilateral first I get equilateral. I can't understand what's happening?

like image 841
kartikeykant18 Avatar asked Oct 29 '25 01:10

kartikeykant18


2 Answers

You shouldn't use else in this case.

Code:

if (condition)
     code
else if (condition2)
     code2

Checks if condition is true. If so it executes code. Only if condition is false, condition2 is checked and code2 could be executed.

like image 74
Ari Avatar answered Oct 30 '25 18:10

Ari


Your code "checks" the second if only when the first if is false.
logically the second if can be true only if the first if is true...

I would change the code to:

if (side1 == side2 || side2 == side3 || side1 == side3)
{
    printf("Isosceles triangle.");
    if (side1 == side2 && side2 == side3 && side3 == side1)
        printf("equilateral triangle");
}
like image 44
Roee Gavirel Avatar answered Oct 30 '25 16:10

Roee Gavirel