Topic 42 of 100 Control Flow in C Interactive Tutorial

Choosing Between Alternatives With if...else in C

11 mins read Last updated: 22 Aug 2026 24,200 views
C Compiler 0.00%

What is Choosing Between Alternatives With if...else in C? Core Concept & Direct Summary

Core Objective & Problem Statement

How do two-way `if...else` and multi-way `else if` ladders handle mutually exclusive decision branches?

Direct Answer Summary

In the last tutorial, the plain if statement taught our programs to ask a question: "Is this true? If so, do something." But it left an awkward gap — when the answer was "no," the program just shrugged and moved on. No alternative. No response.

Real decisions have two sides. If the password is correct, log in — else, show an error. If it's a weekday, set the alarm — else, sleep in. That second path is exactly what else adds to your toolkit, and its big brother, the else if ladder, extends the idea to as many outcomes as you need.

Let's build both, step by step — and along the way, fix the ATM program from last time, which quietly had a design flaw you may not have noticed.

(Suggested image: the if-else flowchart — condition diamond splitting into "true" and "false" paths, each with its own block, then rejoining below. This is the hero graphic.)


How Does Choosing Between Alternatives With if...else in C Work? In-Depth Mechanics & Architecture

The Basic Syntax

main.c
Run Online
if (condition) {
    // runs when condition is TRUE
} else {
    // runs when condition is FALSE
}

The contract is simple and beautiful: exactly one of the two blocks always runs. Never both. Never neither. One path or the other, every single time.

A first example:

main.c
Run Online
#include <stdio.h>
int main() {
    int number;
    printf("Enter a number: ");
    scanf("%d", &number);
    if (number % 2 == 0) {
        printf("%d is even.\n", number);
    } else {
        printf("%d is odd.\n", number);
    }
    return 0;
}

Two runs:

main.c
Run Online
Enter a number: 1414 is even.

Even or odd — every integer on Earth falls into one basket or the other. That's a perfect if-else: two mutually exclusive outcomes.


Why Not Just Use Two if Statements?

Fair question. This works too:

main.c
Run Online
if (number % 2 == 0) {
    printf("even\n");
}
if (number % 2 != 0) {
    printf("odd\n");
}

So why does else exist? Three reasons:

1. Efficiency. With two ifs, the program checks both conditions every time — even after the first one matched. With if-else, a true condition means the else is skipped entirely.

2. Safety. If you later modify the first condition but forget to update the second to match, the two ifs can drift out of sync — and suddenly both blocks run, or neither does. if-else can't drift; the alternative is automatic.

3. Intent. if-else tells the reader "these are the two sides of one decision." Two separate ifs say "these are two unrelated checks." Code that communicates intent is code that's easier to maintain.

Remember the ATM example from the if tutorial? It used three independent if statements — and that was a flaw. A withdrawal of -500 would print "Invalid amount" and then still get checked against the other conditions. With if-else, invalid input takes one path and never touches the rest. That's the correct design, and we're about to build it.


The else if Ladder: Handling Many Outcomes

Two outcomes need if-else. What about five? That's the else if ladder:

main.c
Run Online
if (condition1) {
    // runs if condition1 is true
} else if (condition2) {
    // runs ONLY if condition1 was false AND condition2 is true
} else if (condition3) {
    // runs ONLY if everything above was false AND condition3 is true
} else {
    // runs when NOTHING above matched
}

How it executes: C checks conditions top to bottom, runs the first one that's true, then jumps to the very end — skipping everything below. If nothing matches, the final else catches it.

The classic example — grading:

main.c
Run Online
#include <stdio.h>
int main() {
    int marks;
    printf("Enter marks (0-100): ");
    scanf("%d", &marks);
    if (marks >= 90) {
        puts("Grade: A — Outstanding!");
    } else if (marks >= 75) {
        puts("Grade: B — Great job!");
    } else if (marks >= 60) {
        puts("Grade: C — Good effort.");
    } else if (marks >= 40) {
        puts("Grade: D — You passed.");
    } else {
        puts("Grade: F — Better luck next time.");
    }
    return 0;
}

Sample Run:

main.c
Run Online
Enter marks(0-100): 82Grade: B — Great job!

(Suggested image: the ladder diagram — four condition diamonds stacked vertically, each "false" arrow feeding the next diamond, each "true" arrow leading to its grade, then all paths rejoining. Visual learners NEED this one.)


Order Matters — The Golden Rule of Ladders

Here's a trap that catches nearly everyone once. What happens if we flip the ladder upside down?

main.c
Run Online
int marks = 82;
if (marks >= 40) {
    // 82 >= 40 → TRUE! Ladder stops here.    puts("Grade: D");
} else if (marks >= 60) {
    // never reached    puts("Grade: C");
} else if (marks >= 75) {
    // never reached    puts("Grade: B");
} else if (marks >= 90) {
    // never reached    puts("Grade: A");
}

Output: Grade: D — for 82 marks! 😱

Since the ladder stops at the first true condition, putting a loose condition (>= 40) above a strict one (>= 90) means the strict one never gets a chance. The rule:

Always order conditions from most specific (highest bar) to most general (lowest bar).

Think of it like a bouncer with a guest list: check for VIPs first, regulars second, everyone else last.


Fixing the ATM: if-else Done Right

Here's the withdrawal program from the if tutorial, rebuilt properly:

main.c
Run Online
#include <stdio.h>
int main() {
    float balance = 5000.00;
    float amount;
    printf("Enter withdrawal amount: ");
    scanf("%f", &amount);
    if (amount <= 0) {
        puts("Invalid amount. Must be positive.");
    } else if (amount > balance) {
        printf("Insufficient funds. Balance: %.2f\n", balance);
    } else {
        balance -= amount;
        printf("Withdrawal successful!\n");
        printf("Remaining balance: %.2f\n", balance);
    }
    return 0;
}

Sample Runs:

main.c
Run Online
Enter withdrawal amount: -200Invalid amount. Must be positive.
main.c
Run Online
Enter withdrawal amount: 9999Insufficient funds. Balance: 5000.00
main.c
Run Online
Enter withdrawal amount: 1500Withdrawal successful!Remaining balance: 3500.00

Now the three situations are truly mutually exclusive — invalid input can't accidentally fall through into other checks. Each amount takes exactly one path. Compare this to the three-if version and you'll feel the difference: this one is correct by construction, not by luck.


Is the Final else Required?

No — it's optional. A ladder can end on an else if:

main.c
Run Online
if (score >= 50) {
    puts("Passed");
} else if (score >= 40) {
    puts("Grace marks applied");
}
// no else — scores below 40 get NO output at all

Without a final else, it's possible that nothing runs. Sometimes that's exactly what you want. But when you believe you've covered every case, adding a final else with an "unexpected value" message is cheap insurance — it turns silent logic gaps into visible ones:

main.c
Run Online
} else {
    printf("Unexpected value: %d\n", value);
    // helps you catch bugs early
}

Nested if-else: Decisions Within Decisions

if-else structures nest inside each other freely — ideal when a second decision only matters after the first:

main.c
Run Online
int age = 22;
char citizen = 'Y';
if (citizen == 'Y') {
    if (age >= 18) {
        puts("You are eligible to vote.");
    } else {
        printf("You can vote in %d year(s).\n", 18 - age);
    }
} else {
    puts("Voting requires citizenship.");
}

The readability warning from last time applies doubly here: deep nesting is hard to follow. Two levels? Fine. Four levels? Time to rethink — combine conditions with &&, or (once you learn functions) break the logic into pieces.


The Ternary Operator: if-else in One Line

For simple either/or value assignments, C offers a compact shorthand:

main.c
Run Online
// The long way:
int max;
if (a > b) {
    max = a;
} else {
    max = b;
}
// The ternary way:
int max =(a > b) ? a : b;

The pattern is condition ? value_if_true : value_if_false. It's an expression — it produces a value, so it can sit inside assignments and even printf calls:

main.c
Run Online
printf("You are %s.\n",(age >= 18) ? "an adult" : "a minor");
printf("%d is %s.\n", n,(n % 2 == 0) ? "even" : "odd");

Use it sparingly. One-line either/or values? Elegant. Nested ternaries? a ? b : c ? d : e — technically valid, practically unreadable. If it doesn't fit clearly in one line, write the full if-else.

(Suggested image: side-by-side code graphic — 5-line if-else vs 1-line ternary producing the same result)


Common if-else Mistakes

  1. The stray semicolon strikes again — if (x > 5); ends the statement; both blocks then misbehave (the "true" block always runs, and the else becomes orphaned, causing a compile error about else without if).
  2. Upside-down ladders — loose conditions above strict ones. Most specific first, always.
  3. else without braces swallowing wrong code — same single-statement trap as if. Braces everywhere, always.
  4. Redundant conditions — writing else if (marks < 40) after a ladder that already eliminated everything >= 40. The conditions in a ladder only see what survived the checks above; use that.
  5. Giant ladders that want to be a switch — comparing one variable against ten fixed values? That's switch territory (next tutorial). Ladders shine with ranges; switches shine with exact values.

(Suggested image: "5 if-else Mistakes" checklist graphic, consistent with the series)


When to Use What: The Decision Cheat Sheet

SituationBest Tool
One condition, do-or-skipif
Two mutually exclusive outcomesif-else
Multiple ranges or varied conditionselse if ladder
One variable vs. many exact valuesswitch (next tutorial)
Simple either/or assignmentTernary ? :

Final Thoughts

if-else completes the decision-making foundation: the if asks the question, and the else guarantees an answer either way. Add the else if ladder, and you can sort any input into any number of buckets — as long as you remember the golden rule: most specific first.

You now have everything needed for decisions based on ranges and complex conditions. But there's one shape of decision we haven't optimized yet — one variable, many exact values. That's the specialty of switch, and it's the next stop.


Runnable C Code Example & Practical Implementation

main.c
Run Online
#include <stdio.h>
int main() {
    int score = 82;
    char grade;
    if (score >= 90) {
        grade = 'A';
    } else if (score >= 80) {
        grade = 'B';
    } else if (score >= 70) {
        grade = 'C';
    } else if (score >= 60) {
        grade = 'D';
    } else {
        grade = 'F';
    }
    printf("Score: %d -> Grade: %c\
", score, grade);
    return 0;
}

Key Takeaways, Best Practices & Memory Safety Rules

Best Practice & Key Takeaways
Always include a fallback else block in multi-branch ladders to handle unexpected input or error conditions.

Frequently Asked Questions & Technical Interview Insights

Technical Interview & Viva Questions

Frequently asked C programming interview questions
Q

Q: What is the 'dangling else' problem in C, and how does the compiler resolve it?

A: In nested `if` statements without braces, an `else` binds to the closest preceding unmatched `if`.
Q

Q: How do you force an `else` to attach to an outer `if`?

A: Enclose the inner `if` block in explicit curly braces `{ ... }`.

Related Tools, Tutorials & Authoritative References

Recommended Interactive Tools

Authoritative Standards & Citations