C Fundamentals

Control Flow in C

Master decision-making and loops: if-else, switch-case, for, while, do-while. Learn how programs make choices and repeat actions.

๐ŸŽฏ What is Control Flow?

By default, C programs execute statements sequentially (line by line). But real-world programs need to make decisions and repeat actions. Control flow statements let you:

๐Ÿ’ก Three Types of Control Flow

  • Sequential - Execute one after another (default)
  • Conditional - Execute only if a condition is true (if-else, switch)
  • Iterative - Repeat multiple times (loops: for, while, do-while)

๐Ÿ”€ If-Else Statements

The if statement is like asking a yes/no question. If the answer is "yes" (true), execute some code. If "no" (false), skip it or do something else.

๐Ÿค” How If-Else Works (Real-world Analogy)

Imagine a traffic light:

  • if (light is green) โ†’ Go
  • else if (light is yellow) โ†’ Slow down
  • else (light is red) โ†’ Stop

1. Simple If Statement

Use when you want to do something only if a condition is true.

simple_if.c
#include <stdio.h>

int main() {
    int age;
    printf("Enter your age: ");
    scanf("%d", &age);
    
    // Simple if - executes only if condition is true
    if (age >= 18) {
        printf("You are an adult!\n");
    }
    
    // This always executes (not inside if)
    printf("Thanks for using our program.\n");
    
    return 0;
}

๐Ÿ“‹ Execution Flow

  1. Program asks for age
  2. Checks: Is age >= 18?
    • If YES โ†’ Print "You are an adult!"
    • If NO โ†’ Skip the if block entirely
  3. Print "Thanks for using our program." (always runs)

2. If-Else Statement

Use when you have two choices: do this OR do that.

if_else.c
#include <stdio.h>

int main() {
    int num;
    printf("Enter a number: ");
    scanf("%d", &num);
    
    // Check if number is even or odd
    if (num % 2 == 0) {
        // This block runs if remainder is 0 (even)
        printf("%d is EVEN\n", num);
    } else {
        // This block runs if condition is false (odd)
        printf("%d is ODD\n", num);
    }
    
    return 0;
}

๐Ÿงฎ Understanding the Condition: num % 2 == 0

  • % is the modulo operator (gives remainder)
  • num % 2 gives the remainder when divided by 2
  • Even numbers รท 2 have remainder 0
  • Odd numbers รท 2 have remainder 1
  • == checks if two values are equal

3. If-Else If-Else Ladder

Use when you have multiple conditions to check in order.

if_else_ladder.c
#include <stdio.h>

int main() {
    int score;
    printf("Enter your score (0-100): ");
    scanf("%d", &score);
    
    // Multiple conditions checked in order
    if (score >= 90) {
        printf("Grade: A (Excellent!)\n");
    } else if (score >= 80) {
        printf("Grade: B (Good job!)\n");
    } else if (score >= 70) {
        printf("Grade: C (Average)\n");
    } else if (score >= 60) {
        printf("Grade: D (Needs improvement)\n");
    } else {
        printf("Grade: F (Failed)\n");
    }
    
    return 0;
}

๐Ÿ“‹ How the Ladder Works

  1. Check: score >= 90? If yes โ†’ Grade A, STOP
  2. If no, check: score >= 80? If yes โ†’ Grade B, STOP
  3. If no, check: score >= 70? If yes โ†’ Grade C, STOP
  4. If no, check: score >= 60? If yes โ†’ Grade D, STOP
  5. If none above โ†’ else block runs โ†’ Grade F

Important: Only ONE block runs! Once a condition is true, the rest are skipped.

4. Nested If Statements

An if statement inside another if statement.

nested_if.c
#include <stdio.h>

int main() {
    int age;
    char hasLicense;
    
    printf("Enter your age: ");
    scanf("%d", &age);
    
    printf("Do you have a license? (y/n): ");
    scanf(" %c", &hasLicense);  // Space before %c skips whitespace
    
    // Outer if
    if (age >= 18) {
        printf("You are old enough to drive.\n");
        
        // Inner if - only checks if outer is true
        if (hasLicense == 'y' || hasLicense == 'Y') {
            printf("And you have a license! You can drive.\n");
        } else {
            printf("But you need a license to drive.\n");
        }
    } else {
        printf("You are too young to drive.\n");
    }
    
    return 0;
}

5. Ternary Operator (Shorthand If-Else)

A compact way to write simple if-else: condition ? value_if_true : value_if_false

ternary.c
#include <stdio.h>

int main() {
    int a = 10, b = 20;
    
    // Long way with if-else
    int max;
    if (a > b) {
        max = a;
    } else {
        max = b;
    }
    
    // Short way with ternary operator
    int max2 = (a > b) ? a : b;
    
    // Can also use directly in printf
    printf("Maximum is: %d\n", (a > b) ? a : b);
    
    // Check even/odd
    int num = 15;
    printf("%d is %s\n", num, (num % 2 == 0) ? "even" : "odd");
    
    return 0;
}

๐ŸŽš๏ธ Switch Statement

Use switch when you need to compare one variable against multiple constant values. It's cleaner than a long if-else ladder.

๐Ÿค” When to Use Switch vs If-Else

Use Switch When... Use If-Else When...
Checking one variable against exact values Checking ranges (age > 18)
Values are integers or characters Conditions are complex
Code readability matters Need floating-point checks

1. Basic Switch Syntax

switch_basics.c
#include <stdio.h>

int main() {
    int day;
    printf("Enter day number (1-7): ");
    scanf("%d", &day);
    
    switch(day) {
        case 1:
            printf("Sunday\n");
            break;  // Exit switch after this case
        case 2:
            printf("Monday\n");
            break;
        case 3:
            printf("Tuesday\n");
            break;
        case 4:
            printf("Wednesday\n");
            break;
        case 5:
            printf("Thursday\n");
            break;
        case 6:
            printf("Friday\n");
            break;
        case 7:
            printf("Saturday\n");
            break;
        default:
            printf("Invalid day! Please enter 1-7.\n");
    }
    
    return 0;
}

๐Ÿ“‹ How Switch Works

  1. Evaluate the expression in switch(expression)
  2. Jump to the case that matches the value
  3. Execute statements from that case onward
  4. break exits the switch statement
  5. If no case matches, default runs (if present)

โš ๏ธ The "Fall-Through" Behavior

Without break, execution continues to the NEXT case! This is called "fall-through".

fallthrough.c
switch(grade) {
    case 'A':
        printf("Excellent! ");
        // No break! Falls through to B
    case 'B':
        printf("Good job! ");
        // No break! Falls through to C
    case 'C':
        printf("Passed.\n");
        break;  // Now stops
}

Output for grade 'A': "Excellent! Good job! Passed."

Lesson: Always use break unless you intentionally want fall-through!

2. Calculator Using Switch

calculator.c
#include <stdio.h>

int main() {
    char operator;
    double num1, num2, result;
    
    printf("Enter an operator (+, -, *, /): ");
    scanf(" %c", &operator);  // Space before %c
    
    printf("Enter two numbers: ");
    scanf("%lf %lf", &num1, &num2);
    
    switch(operator) {
        case '+':
            result = num1 + num2;
            printf("%.2lf + %.2lf = %.2lf\n", num1, num2, result);
            break;
            
        case '-':
            result = num1 - num2;
            printf("%.2lf - %.2lf = %.2lf\n", num1, num2, result);
            break;
            
        case '*':
            result = num1 * num2;
            printf("%.2lf * %.2lf = %.2lf\n", num1, num2, result);
            break;
            
        case '/':
            if (num2 != 0) {
                result = num1 / num2;
                printf("%.2lf / %.2lf = %.2lf\n", num1, num2, result);
            } else {
                printf("Error: Cannot divide by zero!\n");
            }
            break;
            
        default:
            printf("Invalid operator! Use +, -, *, or /\n");
    }
    
    return 0;
}

๐Ÿ’ก Key Points

  • switch works with int, char, and enum types
  • case values must be constants (not variables)
  • Multiple cases can share the same code:
switch(grade) {
    case 'A':
    case 'a':
        printf("Excellent!\n");
        break;
    case 'B':
    case 'b':
        printf("Good!\n");
        break;
}

๐Ÿ”„ Loops in C

Loops let you execute code multiple times without writing it repeatedly. Imagine printing numbers 1 to 1000 - loops make this easy!

๐Ÿ”ข For Loop

Best when you know how many times to repeat (counting)

โฑ๏ธ While Loop

Best when you don't know the count, but know when to stop

โœ… Do-While Loop

Best when you need to run at least once

1. For Loop

Structure: for(initialize; condition; update)

๐Ÿ”„ For Loop Flow

  1. Initialize: Set starting value (runs once)
  2. Condition: Check if we should continue
  3. Execute: Run the loop body
  4. Update: Change the counter
  5. Repeat: Go back to step 2
for_loop.c
#include <stdio.h>

int main() {
    // Example 1: Print 1 to 5
    printf("Counting 1 to 5:\n");
    for (int i = 1; i <= 5; i++) {
        printf("%d ", i);
    }
    printf("\n\n");
    
    // Example 2: Count backwards
    printf("Counting 5 to 1:\n");
    for (int i = 5; i >= 1; i--) {
        printf("%d ", i);
    }
    printf("\n\n");
    
    // Example 3: Sum of first 10 numbers
    int sum = 0;
    for (int i = 1; i <= 10; i++) {
        sum = sum + i;  // or sum += i
    }
    printf("Sum of 1 to 10 = %d\n\n", sum);
    
    // Example 4: Multiplication table
    int num = 7;
    printf("Multiplication table of %d:\n", num);
    for (int i = 1; i <= 10; i++) {
        printf("%d x %d = %d\n", num, i, num * i);
    }
    
    return 0;
}

๐Ÿ“‹ Dry Run: Sum of 1 to 10

Iteration i value sum before sum after (sum += i) Condition
11011<=10 โœ“
22132<=10 โœ“
33363<=10 โœ“
...............
1010455510<=10 โœ“
End1155-11<=10 โœ—

Final result: sum = 55

2. While Loop

Checks condition first, then executes. Might run zero times!

while_loop.c
#include <stdio.h>

int main() {
    // Example 1: Basic counting
    int i = 1;           // Initialize before loop
    while (i <= 5) {     // Check condition
        printf("%d ", i);
        i++;             // Update inside loop
    }
    printf("\n\n");
    
    // Example 2: Count digits in a number
    int num, count = 0;
    printf("Enter a number: ");
    scanf("%d", &num);
    
    int temp = num;
    while (temp != 0) {
        temp = temp / 10;  // Remove last digit
        count++;           // Count one digit
    }
    printf("Number of digits in %d = %d\n\n", num, count);
    
    // Example 3: Reverse a number
    temp = num;
    int reversed = 0;
    while (temp != 0) {
        int digit = temp % 10;           // Get last digit
        reversed = reversed * 10 + digit; // Append to result
        temp = temp / 10;                 // Remove last digit
    }
    printf("Reversed: %d\n", reversed);
    
    return 0;
}

๐Ÿ”„ Reverse Number Example: Step by Step

For input 1234:

Step temp digit (temp%10) reversed (reversed*10+digit)
Start1234-0
112340*10+4 = 4
21234*10+3 = 43
31243*10+2 = 432
401432*10+1 = 4321

3. Do-While Loop

Executes first, then checks. Always runs at least once!

do_while.c
#include <stdio.h>

int main() {
    // Menu-driven program (classic do-while use case)
    int choice;
    
    do {
        printf("\n===== MENU =====\n");
        printf("1. Print Hello\n");
        printf("2. Print Current Date\n");
        printf("3. Exit\n");
        printf("Enter your choice: ");
        scanf("%d", &choice);
        
        switch(choice) {
            case 1:
                printf("Hello, World!\n");
                break;
            case 2:
                printf("Today's date: April 18, 2026\n");
                break;
            case 3:
                printf("Goodbye!\n");
                break;
            default:
                printf("Invalid choice! Try again.\n");
        }
        
    } while (choice != 3);  // Continue until user chooses 3
    
    printf("Program ended.\n");
    
    return 0;
}

๐Ÿ”„ For vs While vs Do-While Comparison

Feature For Loop While Loop Do-While
When to use Known iterations Unknown iterations At least once
Condition check Before execution Before execution After execution
Minimum runs 0 times 0 times 1 time

4. Nested Loops

A loop inside another loop. Useful for patterns and 2D structures.

nested_loops.c
#include <stdio.h>

int main() {
    // Pattern: Right triangle
    printf("Right Triangle Pattern:\n");
    for (int i = 1; i <= 5; i++) {      // Outer loop: rows
        for (int j = 1; j <= i; j++) {  // Inner loop: columns
            printf("* ");
        }
        printf("\n");  // New line after each row
    }
    
    // Output:
    // * 
    // * * 
    // * * * 
    // * * * * 
    // * * * * * 
    
    printf("\nMultiplication Table (1-5):\n");
    for (int i = 1; i <= 5; i++) {
        for (int j = 1; j <= 5; j++) {
            printf("%4d", i * j);  // %4d for alignment
        }
        printf("\n");
    }
    
    return 0;
}

๐Ÿ›‘ Control Statements: break & continue

โน๏ธ break

Immediately exit the loop/switch. Jump to the next statement after the loop.

โญ๏ธ continue

Skip the rest of current iteration. Jump to the next iteration.

break_continue.c
#include <stdio.h>

int main() {
    // break example: Find first number divisible by 7
    printf("First number > 50 divisible by 7: ");
    for (int i = 51; i <= 100; i++) {
        if (i % 7 == 0) {
            printf("%d\n", i);
            break;  // Exit loop immediately
        }
    }
    
    // continue example: Print only odd numbers
    printf("Odd numbers from 1 to 10: ");
    for (int i = 1; i <= 10; i++) {
        if (i % 2 == 0) {
            continue;  // Skip even numbers
        }
        printf("%d ", i);  // Only runs for odd numbers
    }
    printf("\n");
    
    // Real-world: Skip invalid inputs
    printf("\nProcessing valid scores only:\n");
    int scores[] = {85, -5, 92, 101, 78, -10, 95};
    int size = 7;
    
    for (int i = 0; i < size; i++) {
        if (scores[i] < 0 || scores[i] > 100) {
            printf("Skipping invalid score: %d\n", scores[i]);
            continue;
        }
        printf("Processing score: %d\n", scores[i]);
    }
    
    return 0;
}

๐Ÿ“Š Visual Comparison

Normal Loop Flow:          With break:              With continue:
โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”           โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”          โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚   Start     โ”‚           โ”‚   Start       โ”‚          โ”‚   Start       โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”˜           โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”˜          โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”˜
       โ”‚                          โ”‚                         โ”‚
       โ–ผ                          โ–ผ                         โ–ผ
โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”           โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”          โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚  Condition? โ”‚           โ”‚  Condition? โ”‚          โ”‚  Condition? โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”˜           โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”˜          โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”˜
   Yes/No                      Yes/No                    Yes/No
    โ”‚ โ”‚                         โ”‚ โ”‚                       โ”‚ โ”‚
   Yes No                      Yes No                    Yes No
    โ”‚ โ”‚                         โ”‚ โ”‚                       โ”‚ โ”‚
    โ–ผ โ–ผ                         โ–ผ โ–ผ                       โ–ผ โ–ผ
โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”  โ”Œโ”€โ”€โ”€โ”€โ”      โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”  โ”Œโ”€โ”€โ”€โ”€โ”       โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”  โ”Œโ”€โ”€โ”€โ”€โ”
โ”‚  Body   โ”‚โ”€โ”€โ”‚End โ”‚      โ”‚  Body   โ”‚โ”€โ”€โ”‚End โ”‚       โ”‚  Body   โ”‚โ”€โ”€โ”‚End โ”‚
โ””โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”˜  โ””โ”€โ”€โ”€โ”€โ”˜      โ””โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”˜  โ””โ”€โ”€โ”€โ”€โ”˜       โ””โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”˜  โ””โ”€โ”€โ”€โ”€โ”˜
     โ”‚                         โ”‚                         โ”‚
     โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜                         โ”‚
                               break โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
                               (jump to End)            
                                                       continue
                               (jump to Condition) โ”€โ”€โ”€โ”€โ”€โ”˜
                        

๐Ÿ“ Summary

Statement Use When... Syntax
if One condition, one action if (cond) { ... }
if-else Two mutually exclusive actions if (cond) { ... } else { ... }
if-else if Multiple conditions to check if (c1) {...} else if (c2) {...}
switch Variable matches constants switch(v) { case 1: ... }
for Known iteration count for (i=0; i<n; i++) { ... }
while Unknown count, condition-based while (cond) { ... }
do-while Must run at least once do { ... } while (cond);