Special Offer Diwali Special Bundle Offer: 3 courses for ₹8,999, save ₹9,001 (50% OFF)! Limited seats available. View Bundles →
0% Completed
Tutorials / C Programming Tutorial / Chapter 2: Operators & Control Flow
C ⏱ 10 min read

Conditional Statements: if, if-else, nested if

Conditional branching directs the flow of execution based on boolean evaluations.

What is it?

The `if`, `else if`, and `else` statements evaluate test expressions enclosed in parentheses `()`.

Why is it used?

Controls decision logic, input range validation, and access permissions in applications.

Detailed Explanation

In C, there is no native primitive boolean keyword in older C89 standards (though C99 introduced `<stdbool.h>`). Any non-zero integer is treated as true, while zero is false. Curly Braces Practice: While single statement `if` branches do not strictly require curly braces `{ ... }`, industry standard C style always mandates braces to prevent dangling-else and indentation bugs.

Syntax Structure

Syntax Blueprint
if (condition) {
    // Code executed when true
} else if (another_condition) {
    // Code
} else {
    // Fallback
}

Code Example

C Code
#include <stdio.h>

int main() {
    int student_score = 82;
    int attendance_pct = 90;
    
    // Nested conditional checks
    if (attendance_pct >= 75) {
        printf("Attendance Requirement: Met (%d%%)\n", attendance_pct);
        
        if (student_score >= 90) {
            printf("Result: Distinction (Grade A+)\n");
        } else if (student_score >= 75) {
            printf("Result: First Class (Grade A)\n");
        } else if (student_score >= 50) {
            printf("Result: Pass (Grade B)\n");
        } else {
            printf("Result: Fail\n");
        }
    } else {
        printf("Error: Student debarred due to shortage of attendance (%d%% < 75%%)\n", attendance_pct);
    }
    
    return 0;
}

Explanation of the Code

• Outer `if` verifies attendance threshold. • Nested `else if` ladder computes grade bracket. • All blocks explicitly wrapped in braces for safety.

Expected Output

Attendance Requirement: Met (90%) Result: First Class (Grade A)

Real-World Application

Used across embedded firmware to check sensor battery thresholds before transmitting radio signals.

Common Mistakes to Avoid

• Writing `if (x = 5)` instead of `if (x == 5)`. The single equals assigns 5 to x, evaluates to true, and always executes the branch! • Omitting curly braces, causing only the first following statement to be bound to the `if`.

Quick Practice Challenge

Write an `if-else` block that determines whether an integer is positive, negative, or zero.

Key Takeaways

• In C, non-zero is true; zero is false. • Always use `==` for comparison, never `=`. • Always wrap conditional bodies in curly braces `{}`.