Lesson 15: The if-else and Nested if statements
The if-else Statement
Provides an alternative path of execution if the primary condition is false.
Syntax: c if (condition) { // Executed if TRUE } else { // Executed if FALSE }
Example
c int balance = 50; if (balance < 100) { printf("Low balance warning.\n"); } else { printf("Balance is sufficient.\n"); }
The if-else if-else Ladder
Used when you have multiple, mutually exclusive conditions to check.
c int grade = 75;
if (grade >= 90) { printf("A"); } else if (grade >= 80) { printf("B"); } else if (grade >= 70) { printf("C"); } else { printf("Fail"); }
Only one block (the first condition met) will be executed.
Nested if Statements
Placing an if statement inside the block of another if or else statement.
c int user_level = 5; bool is_admin = true; // Use <stdbool.h> for clarity in modern C
if (user_level > 3) { if (is_admin) { printf("Admin access granted.\n"); } else { printf("Standard user access granted.\n"); } } else { printf("Access denied: Level too low.\n"); }