02. The If-Else Statement in C

🟢 Difficulty: Beginner | Dual-Branch Execution Control & Mutually Exclusive Paths

📖 Definition

The if-else statement extends single-branch decision control by providing two mutually exclusive execution paths. If the condition expression evaluates to non-zero (true), the if block runs. If the condition evaluates to zero (false), control jumps directly to execute the else block.

🎯 Why It Is Used

  • Binary Choice Routing: Handling pass/fail validations, even/odd tests, authentication success versus failure responses.
  • Guaranteed Action: Guarantees that exactly one of the two code blocks will execute in every program run.

⚙️ How It Works

Assembly-level branching executes a conditional jump (e.g. jz label_else). If true, the if block executes followed by an unconditional jump (jmp label_end) past the else block.

📝 Syntax

if (condition) {
    // Executed when condition is true (non-zero)
} else {
    // Executed when condition is false (zero)
}

🔀 Structural Flow Comparison

Construct Guaranteed Block Execution Use Case Scenario
if (Single)0 or 1 block runsOptional guard check or audit log action
if-else (Dual)EXACTLY 1 block runsBinary alternative selection (e.g. Even vs Odd)

🌱 Beginner Example: Pass / Fail Determination

#include <stdio.h>

int main(void) {
    int score = 72;

    if (score >= 60) {
        printf("Examination Result: PASSED (%d marks)\n", score);
    } else {
        printf("Examination Result: FAILED (%d marks)\n", score);
    }
    return 0;
}

🌼 Intermediate Example: Input Validation with Alternate Fallback

#include <stdio.h>

int main(void) {
    int withdrawal_amount;
    int account_balance = 500;

    printf("Current Balance: $%d\n", account_balance);
    printf("Enter withdrawal amount ($): ");

    if (scanf("%d", &withdrawal_amount) == 1 && withdrawal_amount > 0) {
        if (withdrawal_amount <= account_balance) {
            account_balance -= withdrawal_amount;
            printf("Withdrawal Successful! Remaining Balance: $%d\n", account_balance);
        } else {
            printf("Transaction Declined: Insufficient funds!\n");
        }
    } else {
        printf("Transaction Failed: Invalid numeric input entered.\n");
    }
    return 0;
}

🌲 Advanced Example: Safe Error Status Code Handling

#include <stdio.h>
#include <stdbool.h>

bool write_config_file(const char *filename) {
    if (filename == NULL) return false;
    FILE *f = fopen(filename, "w");
    if (f != NULL) {
        fprintf(f, "STATUS=ACTIVE\n");
        fclose(f);
        return true;
    } else {
        return false;
    }
}

int main(void) {
    if (write_config_file("app.conf")) {
        puts("Configuration file written successfully.");
    } else {
        puts("Error: Failed to write configuration file!");
    }
    return 0;
}

🔍 Line-by-Line Explanation

  • if (withdrawal_amount <= account_balance): Checks whether the account has sufficient funds.
  • account_balance -= withdrawal_amount;: Deducts funds in-place if balance is sufficient.
  • else { printf("Transaction Declined..."); }: Runs if withdrawal exceeds balance.

💻 Expected Terminal Output

Current Balance: $500
Enter withdrawal amount ($): 200
Withdrawal Successful! Remaining Balance: $300
Configuration file written successfully.

⚠️ Common Mistakes & Pitfalls

  • Misplacing Semicolons Before else: Writing if (cond); else causes compilation errors (syntax error on else).
  • Dangling Else Misinterpretation: An else clause always attaches to the nearest preceding if statement unless enclosed by explicit {} braces.

📌 Important Rules & Limitations

  • An else block cannot exist without a corresponding if.
  • Exactly one of the two blocks will execute per evaluation.

🌐 Multilingual Explanation: English

The if-else construct provides two mutually exclusive execution paths. If the condition is non-zero, the if block runs; otherwise, the else block runs.

🌐 Multilingual Explanation: Hindi (Roman Script)

if-else mein do raste hote hain. Agar condition true hai toh if block chalega, warna else block chalega. Dono mein se sirf ek hi block execute hota hai.

🌐 Multilingual Explanation: Marathi (Roman Script)

if-else madhye don paryay astat. Condition true aslyaas if block chaalto, naitar else block chaalto.

❓ Practice Questions

  1. Under what condition will the else block of an if-else statement execute?
  2. What is the dangling else problem and how do curly braces {} resolve it?
  3. Can an else block have a condition expression attached directly to it without if?

🚀 Practical Coding Challenge

Write a C program named parity_checker.c that inputs an integer from the user. Use an if-else statement to determine if the number is even or odd, and print the result.

🧭 Navigation & Breadcrumbs

← Previous: 01. The If Statement | Module 06 Guide | Next: 03. Else-If Ladder →