AlgoViz

If ElseIf

Easy

Branching on a condition

Problem

Use if / else-if / else to run different code depending on a condition. Each condition is checked in order; the first one that is true runs, and the rest are skipped. The final else runs when none matched.

In simple words

Ask questions in order and do the first one whose answer is yes.

The idea

An if / else-if / else chain checks its conditions strictly in order and runs the first branch that is true, skipping the rest. That ordering is the whole meaning: put the most specific condition first, because a broader one above it will swallow every case below.

The trick

  • Only one branch ever runs — the chain stops at the first match.
  • A trailing `else` is your catch-all; leaving it out means some inputs quietly do nothing.
  • Ranges must be ordered narrowest-first: testing `x > 0` before `x > 100` makes the second branch unreachable.
A
B
C
Fail
0
1
2
3
marks78

Step 1 of 3. marks = 78. The ladder is checked from the top, one rung at a time. Values: A, B, C, Fail. marks 78.

1/3
Optimal
timespace
1if (marks >= 90)        print("A")2else if (marks >= 75)   print("B")3else if (marks >= 50)   print("C")4else                    print("Fail")

Input

array
[A, B, C, Fail]
marks
78

Memory

marks
78

Check yourself

3 quick questions about this walkthrough. A wrong answer costs nothing.

Examples

Example 1

Input:
marks = 72
Output:
B
Explanation:
The ladder is checked top to bottom: marks >= 90 is false, >= 80 is false, >= 70 is true, so B prints and the rest is skipped.

Example 2

Input:
marks = 95
Output:
A
Explanation:
The first condition already holds, so nothing below it is even tested. Order matters in an else-if ladder.

Finished the walkthrough? Add it to your streak.