Conditional Statements (if-else & switch)

⚙️ C Language 🟢 Lesson 5 of 20 📅 2026 Edition
Decision-making is at the heart of every real program. C's conditional statements — if, else, and switch — let your program choose between different paths depending on the current data.
1if, else if, else
C Language ▶ Run Code
int marks = 72;

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

Unlike Python's indentation-based blocks, C uses curly braces { } to group statements together. Indentation is purely for human readability in C — the compiler ignores it completely.

2The Conditional (Ternary) Operator

For simple two-way decisions, C offers a compact one-line alternative to if-else:

C Language ▶ Run Code
int age = 20;
char *status = (age >= 18) ? "Adult" : "Minor";
printf("%s\n", status);

The pattern is condition ? value_if_true : value_if_false. Use it for short, simple checks — for anything more complex, a regular if-else is more readable.

3The switch Statement
C Language ▶ Run Code
int day = 3;

switch (day) {
    case 1:
        printf("Monday\n");
        break;
    case 2:
        printf("Tuesday\n");
        break;
    case 3:
        printf("Wednesday\n");
        break;
    default:
        printf("Invalid day\n");
}

switch is often cleaner than a long chain of else if statements when comparing one variable against many exact values. default catches any value that didn't match a case, similar to Python's final else.

4Why break Matters in switch

Without break, execution "falls through" into the next case automatically, running its code too, even if the value didn't match. This is occasionally used intentionally to group several cases together, but forgetting it by accident is a very common source of bugs.

⚠️ Common Mistake: Forgetting break Inside a switch Statement

If you omit break; at the end of a case, C keeps executing every case below it until it finds a break or reaches the end of the switch — regardless of whether those cases actually matched. This "fall-through" behavior is a deliberate C feature, but forgetting it accidentally is one of the most common beginner bugs.

💻 Try It Yourself

Write a program using switch that converts a number from 1-7 into the corresponding day of the week, with a default case for invalid input.

C Language ▶ Run Code
#include <stdio.h>

int main() {
    int day = 5;

    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");
    }
    return 0;
}
Run This in Our Compiler →