kartikeykant18
kartikeykant18

Reputation: 1811

Sequence of if-else if in 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?

Upvotes: 4

Views: 1264

Answers (5)

zztops
zztops

Reputation: 714

Just switch the order of the if statements. Since every equilateral triangle is isosceles, you never make it into the elseif. Make your code read like this:

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

Alternatively, you can nest the equilateral if block inside the isosceles if block if you want both results printed:

if (side1 == side2 || side2 == side3 || side1 == side3){
    if (side1 == side2 && side2 == side3 && side3 == side1){
        printf("Equilateral triangle");
    }
    printf("Isosceles triangle.");
}

Another optimization to consider is that your equilateral check only needs two check to equalities. ie:

(side1 == side2 && side2 == side3) => (side1 == side3)

So, the if statement can read like this:

if (side1 == side2 && side2 == side3)

Upvotes: 1

Roee Gavirel
Roee Gavirel

Reputation: 19443

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");
}

Upvotes: 3

Qiu
Qiu

Reputation: 5761

Side1 = 3, side2 = 3, side = 3, which means that side1 == side2 is true. That's why your program print out "Iosceles". Beacuse first if is true, second won't be checked. It would be only if the first one was false.

Upvotes: 2

sashkello
sashkello

Reputation: 17871

else is executed only if if is not executed. Just remove else and it will be able to print both statements in such case.

Upvotes: 2

Ari
Ari

Reputation: 3127

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.

Upvotes: 5

Related Questions