DSA Factory
Free lessonsProgramming basics · Stage 2 · Making decisions · Step 4

Decisions inside decisions

Put a choice inside another choice, one question at a time. About 9 minutes.

A question, then a follow-up

A doctor asks first: do you have a fever? If you don't, that is the end of it. If you do, she asks a second question: for how many days? The second question only makes sense after the first answer.

Code does this by putting an if inside another if. The inner lines only get a turn when the outer condition is true. You can nest as deep as you like, but each level is more to keep in your head.

Nested if: the inner question only runs when the outer one is true.

Sorting triangles

Here's a good example. Three sticks can only form a triangle if any two of them are together longer than the third. That's the outer question. If it fails, the answer is "impossible".

If it passes, you ask the inner questions: are all three the same length (equilateral)? Are exactly two the same (isosceles)? Otherwise they are all different (scalene).

Check what is possible first, then ask what kind.
In code
if a + b > c and a + c > b and b + c > a:
    if a == b and b == c:
        kind = "equilateral"
    elif a == b or b == c or a == c:
        kind = "isosceles"
    else:
        kind = "scalene"
else:
    kind = "impossible"
Sticks of length 5, 5 and 8
a: 5
0
b: 5
1
c: 8
2
kind: ?
3
question
possible
yes

The outer question: can these sticks make a triangle at all? 5 plus 5 is 10, which is more than 8. The other two pairs pass too.

Move 1 of 4
Quick check

Sticks of length 2, 3 and 6. What kind of triangle do they make?

  1. AImpossible
  2. BScalene
  3. CIsosceles
Show the answer

Impossible. 2 plus 3 is only 5, which is less than 6, so the two short sticks can't reach each other.

Your problem

Triangle kind

You get three stick lengths. If they can't form a triangle (some two sticks together are not longer than the third), return "impossible". Otherwise return "equilateral" if all three are equal, "isosceles" if exactly two are equal, and "scalene" if all are different.

Example
a = 5, b = 5, c = 8 → "isosceles"

1 ≤ a, b, c ≤ 1,000

Solve it in your browserPython, C++, Java or JavaScript. Hints if you get stuck. No sign-up needed.
Start coding