Docs

Control Flow

if, else, and else if Statements

πŸ“– Introduction

Decision-making is fundamental to programming. The if, else, and else if statements allow your program to make choices based on conditions, executing different code paths depending on whether conditions are true or false.


🎯 Flow of Decision Making

                        β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
                        β”‚   Start     β”‚
                        β””β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”˜
                               β”‚
                               β–Ό
                     β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
                     β”‚ Is condition    β”‚
                     β”‚    true?        β”‚
                     β””β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                              β”‚
              β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
              β”‚ Yes                           β”‚ No
              β–Ό                               β–Ό
    β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”             β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
    β”‚ Execute if      β”‚             β”‚ Execute else    β”‚
    β”‚ block           β”‚             β”‚ block (if any)  β”‚
    β””β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”˜             β””β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”˜
             β”‚                               β”‚
             β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                             β”‚
                             β–Ό
                      β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
                      β”‚    End      β”‚
                      β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

πŸ“ The if Statement

Basic Syntax:

if (condition) {
    // Code to execute if condition is true
}

Simple Example:

int age = 18;

if (age >= 18) {
    printf("You are an adult.\n");
}

How It Works:

  1. β€’The condition inside () is evaluated
  2. β€’If the condition is true (non-zero), the code block executes
  3. β€’If the condition is false (zero), the code block is skipped

Single Statement (No Braces):

if (x > 0)
    printf("x is positive\n");

// Or on one line:
if (x > 0) printf("x is positive\n");

⚠️ Best Practice: Always use braces {}, even for single statements, to prevent bugs when code is modified later.


πŸ“‹ The if-else Statement

Syntax:

if (condition) {
    // Code if condition is true
} else {
    // Code if condition is false
}

Example:

int number = 7;

if (number % 2 == 0) {
    printf("%d is even\n", number);
} else {
    printf("%d is odd\n", number);
}

Flowchart:

        β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
        β”‚ number % 2 == 0? β”‚
        β””β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                 β”‚
     Yes         β”‚          No
     β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
     β–Ό                       β–Ό
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”            β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚ Print   β”‚            β”‚ Print   β”‚
β”‚ "even"  β”‚            β”‚ "odd"   β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜            β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

πŸ”— The else if Ladder

Syntax:

if (condition1) {
    // Code if condition1 is true
} else if (condition2) {
    // Code if condition2 is true
} else if (condition3) {
    // Code if condition3 is true
} else {
    // Code if all conditions are false
}

Example - Grade Calculator:

int score = 85;

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");
}

How It Works:

  1. β€’Conditions are evaluated top to bottom
  2. β€’First true condition's block executes
  3. β€’Remaining conditions are skipped
  4. β€’else catches all remaining cases

πŸ—οΈ Nested if Statements

Syntax:

if (outerCondition) {
    if (innerCondition) {
        // Nested block
    }
}

Example:

int age = 25;
int hasLicense = 1;

if (age >= 18) {
    if (hasLicense) {
        printf("You can drive.\n");
    } else {
        printf("You need a license to drive.\n");
    }
} else {
    printf("You are too young to drive.\n");
}

Flowchart:

                β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
                β”‚  age >= 18?     β”‚
                β””β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                         β”‚
         Yes             β”‚             No
         β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
         β–Ό                               β–Ό
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”             β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚  hasLicense?    β”‚             β”‚ "Too young"     β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”˜             β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
         β”‚
  Yes    β”‚    No
  β”Œβ”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”
  β–Ό             β–Ό
β”Œβ”€β”€β”€β”€β”€β”     β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚"Can β”‚     β”‚"Need     β”‚
β”‚drive"β”‚    β”‚license"  β”‚
β””β”€β”€β”€β”€β”€β”˜     β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

⚑ Conditions and Expressions

Relational Operators in Conditions:

OperatorMeaningExample
==Equal tox == 5
!=Not equal tox != 0
<Less thanx < 10
>Greater thanx > 0
<=Less than or equalx <= 100
>=Greater than or equalx >= 1

Logical Operators:

OperatorMeaningExample
&&ANDx > 0 && x < 10
||ORx < 0 || x > 100
!NOT!found

Examples:

// AND - both conditions must be true
if (age >= 18 && hasID) {
    printf("Entry allowed\n");
}

// OR - at least one condition must be true
if (isAdmin || isOwner) {
    printf("Full access granted\n");
}

// NOT - inverts the condition
if (!isLoggedIn) {
    printf("Please log in\n");
}

// Combined conditions
if ((age >= 18 && hasID) || isVIP) {
    printf("Welcome!\n");
}

🎯 Truth in C

In C, conditions are evaluated as integers:

ValueMeaning
0False
Any non-zero valueTrue
int x = 5;

if (x) {         // True (x is non-zero)
    printf("x is non-zero\n");
}

if (0) {         // False
    printf("This never prints\n");
}

if (-1) {        // True (non-zero)
    printf("-1 is considered true\n");
}

⚠️ Common Mistakes

1. Assignment vs Comparison:

// WRONG: Assignment (always true if x != 0)
if (x = 5) {
    printf("This always executes!\n");
}

// CORRECT: Comparison
if (x == 5) {
    printf("x equals 5\n");
}

2. Dangling else Problem:

// Ambiguous - which if does else belong to?
if (a > 0)
    if (b > 0)
        printf("a and b positive\n");
else
    printf("Which condition is this for?\n");

// Clear with braces:
if (a > 0) {
    if (b > 0) {
        printf("a and b positive\n");
    }
} else {
    printf("a is not positive\n");
}

3. Empty Statement:

// WRONG: Semicolon after if creates empty statement
if (x > 0);  // Empty statement executed
{
    printf("Always executes!\n");  // Not part of if
}

// CORRECT:
if (x > 0) {
    printf("x is positive\n");
}

4. Floating-Point Comparison:

float f = 0.1 + 0.2;

// WRONG: Direct comparison
if (f == 0.3) {  // May fail due to precision
    printf("Equal\n");
}

// CORRECT: Use tolerance
if (fabs(f - 0.3) < 0.0001) {
    printf("Approximately equal\n");
}

πŸ“ The Ternary Operator (Conditional Expression)

A compact form of if-else for simple assignments:

Syntax:

result = (condition) ? value_if_true : value_if_false;

Examples:

// Traditional if-else
int max;
if (a > b) {
    max = a;
} else {
    max = b;
}

// Using ternary operator
int max = (a > b) ? a : b;

// In printf
printf("Status: %s\n", (isActive) ? "Active" : "Inactive");

// Nested ternary (use sparingly)
char grade = (score >= 90) ? 'A' :
             (score >= 80) ? 'B' :
             (score >= 70) ? 'C' : 'F';

πŸ”’ Multiple Conditions Pattern

Range Checking:

// Check if value is in range [0, 100]
if (value >= 0 && value <= 100) {
    printf("Value is in valid range\n");
}

// Check if character is a digit
if (ch >= '0' && ch <= '9') {
    printf("Character is a digit\n");
}

// Check if character is a letter
if ((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z')) {
    printf("Character is a letter\n");
}

Validation Chain:

int validate(int age, int income, int score) {
    if (age < 18) {
        printf("Must be 18 or older\n");
        return 0;
    }

    if (income < 30000) {
        printf("Income too low\n");
        return 0;
    }

    if (score < 650) {
        printf("Credit score too low\n");
        return 0;
    }

    printf("Application approved!\n");
    return 1;
}

πŸ“Š Short-Circuit Evaluation

Logical operators evaluate left-to-right and stop early:

AND (&&):

  • β€’If left side is false, right side is not evaluated
// Safe: division only happens if b != 0
if (b != 0 && a / b > 2) {
    printf("Ratio is greater than 2\n");
}

OR (||):

  • β€’If left side is true, right side is not evaluated
// If isAdmin is true, hasPermission() is not called
if (isAdmin || hasPermission()) {
    grantAccess();
}

🏷️ Best Practices

  1. β€’Always use braces for clarity
  2. β€’Put constants on the left in comparisons (Yoda conditions)
    if (5 == x)  // Compiler error if you write = instead of ==
    
  3. β€’Keep conditions simple - extract complex logic to variables
    int isValidUser = (age >= 18 && hasAccount && !isBanned);
    if (isValidUser) { ... }
    
  4. β€’Order conditions by likelihood for efficiency
  5. β€’Avoid deep nesting - consider early returns
  6. β€’Use meaningful variable names that read like English

βœ… Summary

StatementPurpose
ifExecute code when condition is true
elseExecute code when if condition is false
else ifCheck additional conditions
Nested ifCheck conditions within conditions
Ternary ?:Compact if-else for expressions

πŸ”‘ Key Takeaways

  1. β€’if evaluates a condition and executes code if true
  2. β€’else provides an alternative path when if is false
  3. β€’else if allows multiple condition checking
  4. β€’Use == for comparison, not =
  5. β€’Non-zero values are true, zero is false
  6. β€’Logical operators &&, ||, ! combine conditions
  7. β€’Ternary operator offers compact conditional expressions
  8. β€’Always use braces for code blocks

⏭️ Next Topic

Continue to switch-case statements for multi-way branching.

Control Flow - C Programming Tutorial | DeepML