Conditionals in C: if, if-else, else-if and switch with runnable examples

Learn how C chooses a path through a program. Predict and trace complete examples covering conditions, ladders, logical operators, nesting and switch.

KnowledgeGate Team

Exam prep & CS education

Updated 4 Aug 20266 min read

C statements run from top to bottom until a condition redirects them. A condition in C is nothing more than an integer expression: 0 means false, every other value means true, and if, if-else, the else-if ladder and switch all act on that value, alone or nested inside one another. Predict the output of every program below before you compile it. The errors that cost marks, a stray = or a missing break, are exactly the ones fluent reading hides.

What a conditional means in C

A condition controls whether a block runs. C treats 0 as false and every non-zero value as true, including a negative value. Comparison and logical operators produce 0 or 1.

int zero = 0, debt = -7;

if (zero) { printf("Skipped\n"); }
if (debt) { printf("Debt is non-zero\n"); }

The first block is skipped. The second runs because -7 is non-zero.

The comparison operators are >, <, >=, <=, == and !=. Use && for AND, || for OR and ! for NOT. Parentheses and braces make your intent visible even where C permits omission. One trap hides under the comparison operators: mix a signed and an unsigned operand and -1 > 0u evaluates to true, because the signed value converts to a large unsigned value before the comparison happens. The conversion rules behind that are worked out in Data Types and Operators in C.

Start with if and if-else

Here is one guarded action:

#include <stdio.h>

int main(void) {
    int age = 19;
    if (age >= 18) {
        printf("Eligible to vote\n");
    }
    return 0;
}

Output: Eligible to vote

The expression 19 >= 18 becomes 1, so the block runs. For two possible outcomes, add else and change only the age:

#include <stdio.h>

int main(void) {
    int age = 16;
    if (age >= 18) {
        printf("Eligible to vote\n");
    } else {
        printf("Not eligible yet\n");
    }
    return 0;
}

Output: Not eligible yet

Now 16 >= 18 becomes 0, so control moves to else. An else belongs to the nearest unmatched if. Keep the braces even when a branch holds a single statement, so that pairing stays visible to the next reader.

Choose among several paths with an else-if ladder

Use a ladder when ordered tests must select exactly one path:

#include <stdio.h>

int main(void) {
    int score = 82;

    if (score >= 90) {
        printf("Grade A\n");
    } else if (score >= 75) {
        printf("Grade B\n");
    } else if (score >= 60) {
        printf("Grade C\n");
    } else {
        printf("Grade D\n");
    }

    return 0;
}

Trace it top to bottom. 82 >= 90 is false. 82 >= 75 is true, so the program prints Grade B; later conditions are not evaluated. At the boundaries, 90 gives A, 75 gives B, 60 gives C and 59 gives D. Descending order matters because the first true branch wins. Separate if statements could run more than once, but exactly one branch of this ladder runs.

Flowchart of the grade ladder for score 82: the score above 90 test is false, the above 75 test is true and Grade B prints, while the remaining tests stay greyed out unevaluated.

Combine conditions safely, then understand nesting

With int age = 21, has_id = 1;, the condition age >= 18 && has_id is true, so an if-else prints Entry allowed. Change only has_id to 0, and it prints Entry denied. OR needs either operand to be true, while NOT reverses truth.

Short-circuiting can prevent an invalid operation:

#include <stdio.h>

int main(void) {
    int numerator = 12, denominator = 0;
    if (denominator != 0 && numerator / denominator > 2) {
        printf("Ratio is above 2\n");
    } else {
        printf("Cannot evaluate ratio\n");
    }
    return 0;
}

Output: Cannot evaluate ratio. The left operand is false, so C never attempts the division.

The age check could be nested:

if (age >= 18) {
    if (has_id) {
        printf("Entry allowed\n");
    }
}

A flat && is clearer here. Reserve nesting for a second decision that genuinely depends on entering the first branch.

Use switch for exact-value choices

switch compares one integral, character or enum expression with fixed case labels. It does not directly express a range such as score >= 75.

#include <stdio.h>

int main(void) {
    int a = 14, b = 5;
    char op = '-';

    switch (op) {
        case '+': printf("Sum = %d\n", a + b); break;
        case '-': printf("Difference = %d\n", a - b); break;
        case '*': printf("Product = %d\n", a * b); break;
        case '/':
            if (b != 0) { printf("Quotient = %d\n", a / b); }
            else { printf("Cannot divide by zero\n"); }
            break;
        default: printf("Unsupported operator\n"); break;
    }
    return 0;
}

Since 14 - 5 = 9, the output is Difference = 9. Change only op to '%', and the output is Unsupported operator. Delete the break after case '-' and the same run prints Difference = 9 and then Product = 70, because control falls straight into the next case body without retesting its label.

Branch diagram of the switch on op: the minus arm is highlighted and carries 14 minus 5 to Difference = 9 and then to break exiting the switch, with the plus, star, slash and default arms greyed out.

Common conditional mistakes and how to debug them

In if (n = 0), with n initially 5, assignment changes n to 0, then the block is skipped. Comparison requires if (n == 0). Compile with -Wall and the compiler flags exactly this line, suggesting parentheses around an assignment used as a truth value. Similarly, 0 < x < 10 is not a range test in C. It groups as (0 < x) < 10, so for x = 12 the inner comparison yields 1 and 1 < 10 is true: the broken test wrongly accepts 12. Write x > 0 && x < 10 instead, which is true for x = 7 and false for x = 12.

This else pairs with the inner if, regardless of indentation:

if (logged_in)
    if (is_admin)
        printf("Admin\n");
    else
        printf("Regular user\n");

Make the intended pairing explicit:

if (logged_in) {
    if (is_admin) {
        printf("Admin\n");
    }
} else {
    printf("Please log in\n");
}

Indentation alone does not change C grammar. Also check for missing break, broad ladder tests placed before narrow ones, and accidental semicolons: if (ready); gives the if an empty body, so the block written under it runs unconditionally. To debug, write each operand value, reduce the condition to 0 or 1, identify the selected branch, then run the program.

How coding tests probe conditionals, plus three exercises

Coding tests probe conditionals in four recurring forms: predict the printed output, find the off-by-one at a boundary such as a score of exactly 75, name which branch of a ladder runs, and repair a condition that compiles cleanly but decides wrongly.

Consider int x = 6, y = 9; followed by if (x++ > 6 && ++y > 9). The left comparison uses 6 > 6, which is false; the postfix increment still makes x become 7. Short-circuiting skips ++y, so printf("%d %d", x, y); prints 7 9.

Try before checking:

  1. Find the largest of a = 17, b = 29, c = 11. Answer: 29.

  2. Apply year % 400 == 0 || (year % 4 == 0 && year % 100 != 0) to 2100. Answer: not a leap year, because the first test is false and the parenthesised right side is also false.

  3. Run the switch calculator with a = 18, b = 6, op = '/'. Answer: Quotient = 3.

When you are ready to reason about the cost of larger branch-heavy algorithms, read Time Complexity & Asymptotic Notation.

The short version and the next step

  • Use if for one guarded action.

  • Use if-else for two outcomes.

  • Use an else-if ladder for ordered ranges.

  • Use nesting for dependent decisions.

  • Use switch for fixed exact values.

Keep the habit: predict, trace, compile, test a boundary. For structured practice, continue with the C Language Course. If you want the wider track, the Coding & DSA Courses for Placements page collects the C, C++, Java, Python and data-structure courses. Then watch conditionals do real work inside loops in Sorting Algorithms: Complexity and Comparison.

Now rerun the grade program with 90, 89, 75, 74, 60 and 59. Explain every output without looking at the source.