Conditional Statements

Conditional statements are like traffic lights at an intersection -- when the condition is met, you take one path; otherwise, you take another. Programs gain intelligence through decision-making.

The if Statement

if is the most fundamental conditional. When the condition is true (non-zero), the code inside the braces executes; when false (zero), it is skipped.

C
#include <stdio.h>

int main(void) {
    int score = 95;
    if (score >= 90) {
        printf("Excellent!\n");
    }
    printf("Program continues\n");
    return 0;
}
TEXT
Excellent!
Program continues
💡 Tip: If there is only one statement after if, the braces can be omitted. However, it is strongly recommended to always use braces to avoid logic errors when adding statements later and forgetting to add braces.

The if-else Statement

if-else provides two branches: if the condition is true, the if block executes; if false, the else block executes. One of the two will always run.

C
#include <stdio.h>

int main(void) {
    int age = 16;
    if (age >= 18) {
        printf("You are an adult\n");
    } else {
        printf("You are a minor\n");
    }
    return 0;
}
TEXT
You are a minor

The Dangling else Problem

When multiple if statements are nested, else pairs with the nearest if:

C
#include <stdio.h>

int main(void) {
    int a = 5, b = 0;
    if (a > 10)
        if (b > 0)
            printf("A\n");
    else
        printf("B\n");
    return 0;
}

It looks like the else pairs with the first if, but it actually pairs with the second if, so nothing is printed. Adding braces makes the pairing clear:

C
if (a > 10) {
    if (b > 0) {
        printf("A\n");
    } else {
        printf("B\n");
    }
}
⚠️ Note: Always using braces completely eliminates the dangling else problem.

The if-else if-else Chain

When multiple conditions need to be checked in sequence, use else if to chain multiple branches:

C
#include <stdio.h>

int main(void) {
    int score = 78;
    if (score >= 90) {
        printf("Grade: A\n");
    } else if (score >= 80) {
        printf("Grade: B\n");
    } else if (score >= 70) {
        printf("Grade: C\n");
    } else if (score >= 60) {
        printf("Grade: D\n");
    } else {
        printf("Grade: F\n");
    }
    return 0;
}
TEXT
Grade: C

else if conditions are evaluated from top to bottom. Once a condition is satisfied, all subsequent branches are skipped. The order of conditions matters.

💡 Tip: Place the most likely conditions first for better efficiency; arrange ranges from largest to smallest to avoid logic gaps.

Nested if Statements

An if can be nested inside another if for more refined conditional logic:

C
#include <stdio.h>

int main(void) {
    int age = 25;
    char gender = 'M';
    if (age >= 18) {
        if (gender == 'M') {
            printf("Adult male\n");
        } else {
            printf("Adult female\n");
        }
    } else {
        printf("Minor\n");
    }
    return 0;
}
TEXT
Adult male
⚠️ Note: Nesting should not exceed 3 levels. Too many levels hurt readability. Complex conditions can be combined with logical operators or flattened using else if.

The switch-case Statement

switch jumps to a matching case branch based on the value of an integer expression. It is ideal for branching on discrete values.

Basic Syntax

C
switch (expression) {
    case constant1:
        statement;
        break;
    case constant2:
        statement;
        break;
    default:
        statement;
        break;
}
C
#include <stdio.h>

int main(void) {
    int day = 3;
    switch (day) {
        case 1: printf("Monday\n"); break;
        case 2: printf("Tuesday\n"); break;
        case 3: printf("Wednesday\n"); break;
        case 4: printf("Thursday\n"); break;
        case 5: printf("Friday\n"); break;
        case 6: printf("Saturday\n"); break;
        case 7: printf("Sunday\n"); break;
        default: printf("Invalid day\n"); break;
    }
    return 0;
}
TEXT
Wednesday

The Importance of break

After switch matches a case, it executes all statements from that point onward until it encounters a break or the end of the switch. This is called "fall-through".

C
#include <stdio.h>

int main(void) {
    int num = 2;
    switch (num) {
        case 1: printf("One\n");
        case 2: printf("Two\n");
        case 3: printf("Three\n");
        default: printf("Default\n");
    }
    return 0;
}
TEXT
Two
Three
Default
⚠️ Note: Forgetting break is the most common switch mistake. Unless intentionally using fall-through, always add break at the end of each case.

Using Fall-through to Merge Branches

Sometimes multiple case labels need to execute the same logic. You can deliberately omit break:

C
#include <stdio.h>

int main(void) {
    char grade = 'B';
    switch (grade) {
        case 'A':
        case 'B':
        case 'C':
            printf("Pass\n"); break;
        case 'D':
            printf("Retake\n"); break;
        case 'F':
            printf("Fail\n"); break;
        default:
            printf("Invalid grade\n"); break;
    }
    return 0;
}
TEXT
Pass

Limitations of switch

The Conditional Operator (Ternary)

The conditional operator ?: can replace simple if-else statements. It was introduced in lesson 6; here are more usage examples:

C
#include <stdio.h>

int main(void) {
    int a = -5;
    int abs_a = a >= 0 ? a : -a;
    printf("|%d| = %d\n", a, abs_a);

    int x = 10, y = 10;
    printf("%s\n", x == y ? "Equal" : "Not equal");
    return 0;
}
TEXT
|-5| = 5
Equal
💡 Tip: The conditional operator can be nested, but readability drops quickly. If nesting exceeds one level, use if-else instead.

Example

Determine body type based on BMI, demonstrating multi-branch conditional logic:

C
#include <stdio.h>

int main(void) {
    double weight = 70.0;
    double height = 1.75;
    double bmi = weight / (height * height);

    printf("BMI: %.1f\n", bmi);
    if (bmi < 18.5) {
        printf("Underweight\n");
    } else if (bmi < 24.0) {
        printf("Normal\n");
    } else if (bmi < 28.0) {
        printf("Overweight\n");
    } else {
        printf("Obese\n");
    }
    return 0;
}
▶ Try it Yourself
TEXT
BMI: 22.9
Normal

Example

Implement a simple menu selection using switch:

C
#include <stdio.h>

int main(void) {
    int choice = 2;
    printf("===== Menu =====\n");
    printf("1. New Game\n");
    printf("2. Continue\n");
    printf("3. Settings\n");
    printf("4. Exit\n");
    printf("================\n");
    printf("Your choice: %d\n", choice);

    switch (choice) {
        case 1: printf("Starting new game!\n"); break;
        case 2: printf("Loading save...\n"); break;
        case 3: printf("Opening settings\n"); break;
        case 4: printf("Exiting game\n"); break;
        default: printf("Invalid choice\n"); break;
    }
    return 0;
}
▶ Try it Yourself
TEXT
===== Menu =====
1. New Game
2. Continue
3. Settings
4. Exit
================
Your choice: 2
Loading save...

❓ FAQ

Q When can braces be omitted after if?
A Syntactically, braces can be omitted when there is only one statement after if/else, but it is recommended to always use them to avoid bugs from forgetting to add braces when adding more statements later.
Q Can switch evaluate floating-point numbers or strings?
A No. switch only accepts integer expressions. Neither floating-point numbers nor strings work. To compare strings, use an if-else if chain.
Q Can the default branch be omitted?
A Syntactically yes, but it is recommended to keep it to handle unexpected cases and avoid silent errors from missing values.
Q What is the difference between else if and nested if?
A else if is a flat multi-branch structure that is easier to read; nested if is hierarchical and suitable when conditions depend on each other. They are interchangeable -- choose whichever is more readable.

📖 Summary

📝 Exercises

  1. Write a program that reads an integer and determines whether it is positive, negative, or zero, then prints the result.
  2. Write a program that reads a month number (1-12) and uses switch to output the number of days in that month (assume a non-leap year, so February has 28 days).
  3. Write a program that reads a character and determines whether it is an uppercase letter, a lowercase letter, a digit, or some other character.
100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏