4

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?

kartikeykant18
  • 1,737
  • 6
  • 28
  • 42

5 Answers5

5

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.

Ari
  • 3,101
  • 2
  • 27
  • 49
3

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");
}
Roee Gavirel
  • 18,955
  • 12
  • 67
  • 94
  • 1
    +1 for the nested `if` (instead of just remove the `else`). It implied a equilateral triangle must be a isosceles triangle. – johnchen902 Jul 11 '13 at 13:29
2

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

sashkello
  • 17,306
  • 24
  • 81
  • 109
2

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.

Qiu
  • 5,651
  • 10
  • 49
  • 56
1

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)
zztops
  • 694
  • 1
  • 5
  • 11