Day 5: Control Statements#

Overview#

Control statements determine the flow of a program. They allow us to make decisions and repeat actions. Today we’ll master if/else statements, switch cases, and all types of loops.

What We’ll Learn Today#

  • if and if-else statements
  • else-if chains
  • Switch statements
  • for loops
  • while loops
  • do-while loops
  • break and continue statements
  • Nested loops and conditions

Conditional Statements#

if Statement#

Executes code only if a condition is true:

if (condition) {
    // Code executed if condition is true
}

Simple Example#

#include <stdio.h>

int main() {
    int age = 18;

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

    return 0;
}

if-else Statement#

Executes one block if true, another if false:

if (condition) {
    // Executed if true
} else {
    // Executed if false
}

Example#

#include <stdio.h>

int main() {
    int number;

    printf("Enter a number: ");
    scanf("%d", &number);

    if (number > 0) {
        printf("Positive number\n");
    } else {
        printf("Non-positive number\n");
    }

    return 0;
}

else-if Chain#

Multiple conditions:

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

Practical Example: Grade Assignment#

#include <stdio.h>

int main() {
    int score;

    printf("Enter your score (0-100): ");
    scanf("%d", &score);

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

    return 0;
}

Nested if Statements#

#include <stdio.h>

int main() {
    int age, income;

    printf("Enter age and annual income:\n");
    scanf("%d %d", &age, &income);

    if (age >= 21) {
        if (income >= 30000) {
            printf("Eligible for loan\n");
        } else {
            printf("Income too low\n");
        }
    } else {
        printf("Too young\n");
    }

    return 0;
}

Switch Statement#

When comparing one variable against many values:

switch (expression) {
    case value1:
        // Executed if expression == value1
        break;
    case value2:
        // Executed if expression == value2
        break;
    default:
        // Executed if no case matches
}

Example: Day of Week#

#include <stdio.h>

int main() {
    int day;

    printf("Enter day number (1-7): ");
    scanf("%d", &day);

    switch (day) {
        case 1:
            printf("Monday\n");
            break;
        case 2:
            printf("Tuesday\n");
            break;
        case 3:
            printf("Wednesday\n");
            break;
        case 4:
            printf("Thursday\n");
            break;
        case 5:
            printf("Friday\n");
            break;
        case 6:
            printf("Saturday\n");
            break;
        case 7:
            printf("Sunday\n");
            break;
        default:
            printf("Invalid day\n");
    }

    return 0;
}

Important: Don’t Forget break!#

// ❌ Without break (falls through)
switch (day) {
    case 1:
        printf("Monday\n");
        // Falls through to case 2!
    case 2:
        printf("Tuesday\n");
        break;
}

// ✅ With break (correct)
switch (day) {
    case 1:
        printf("Monday\n");
        break;
    case 2:
        printf("Tuesday\n");
        break;
}

Multiple Cases with Same Action#

switch (day) {
    case 1:
    case 2:
    case 3:
    case 4:
    case 5:
        printf("Weekday\n");
        break;
    case 6:
    case 7:
        printf("Weekend\n");
        break;
}

Loops#

Repeat code multiple times:

for Loop#

Best when you know how many times to repeat:

for (initialization; condition; increment) {
    // Code to repeat
}

Simple for Loop Example#

#include <stdio.h>

int main() {
    // Print numbers 1 to 5
    for (int i = 1; i <= 5; i++) {
        printf("Number: %d\n", i);
    }

    return 0;
}

Output:

Number: 1
Number: 2
Number: 3
Number: 4
Number: 5

for Loop - Step by Step#

for (int i = 1; i <= 5; i++) {
    // INITIALIZATION: int i = 1 (runs once)
    // CONDITION: i <= 5 (checked each iteration)
    // CODE: printf("%d\n", i) (runs if condition true)
    // INCREMENT: i++ (runs after each iteration)
}

More for Loop Examples#

// Count down from 10 to 1
for (int i = 10; i >= 1; i--) {
    printf("%d\n", i);
}

// Print even numbers 2 to 20
for (int i = 2; i <= 20; i += 2) {
    printf("%d\n", i);
}

// Multiplication table
for (int i = 1; i <= 10; i++) {
    printf("5 * %d = %d\n", i, 5 * i);
}

while Loop#

Best when you don’t know how many iterations needed:

while (condition) {
    // Code to repeat
    // Must change condition eventually, or loop runs forever!
}

while Loop Example#

#include <stdio.h>

int main() {
    int count = 1;

    while (count <= 5) {
        printf("Count: %d\n", count);
        count++;  // MUST increment!
    }

    return 0;
}

User Input Example with while#

#include <stdio.h>

int main() {
    int password = 0;
    int correct_password = 12345;

    while (password != correct_password) {
        printf("Enter password: ");
        scanf("%d", &password);

        if (password != correct_password) {
            printf("Wrong password, try again\n");
        }
    }

    printf("Access granted!\n");
    return 0;
}

do-while Loop#

Executes at least once, then checks condition:

do {
    // Code to repeat (runs at least once)
} while (condition);

do-while Example#

#include <stdio.h>

int main() {
    int choice;

    do {
        printf("\n=== Menu ===\n");
        printf("1. Play\n");
        printf("2. Settings\n");
        printf("3. Exit\n");
        printf("Enter choice: ");
        scanf("%d", &choice);

        switch (choice) {
            case 1:
                printf("Starting game...\n");
                break;
            case 2:
                printf("Opening settings...\n");
                break;
            case 3:
                printf("Goodbye!\n");
                break;
            default:
                printf("Invalid choice\n");
        }
    } while (choice != 3);

    return 0;
}

break and continue#

break - Exit the Loop#

#include <stdio.h>

int main() {
    for (int i = 1; i <= 10; i++) {
        if (i == 5) {
            break;  // Exit loop when i equals 5
        }
        printf("%d\n", i);
    }

    return 0;
}

Output:

1
2
3
4

continue - Skip to Next Iteration#

#include <stdio.h>

int main() {
    for (int i = 1; i <= 10; i++) {
        if (i % 2 == 0) {
            continue;  // Skip even numbers
        }
        printf("%d\n", i);
    }

    return 0;
}

Output:

1
3
5
7
9

Nested Loops#

Loops within loops:

Simple Nested Loop Example#

#include <stdio.h>

int main() {
    // Print a 3x3 grid
    for (int i = 1; i <= 3; i++) {
        for (int j = 1; j <= 3; j++) {
            printf("* ");
        }
        printf("\n");
    }

    return 0;
}

Output:

* * *
* * *
* * *

Multiplication Table#

#include <stdio.h>

int main() {
    // Print multiplication table 1-5
    for (int i = 1; i <= 5; i++) {
        for (int j = 1; j <= 5; j++) {
            printf("%d\t", i * j);
        }
        printf("\n");
    }

    return 0;
}

Output:

1	2	3	4	5
2	4	6	8	10
3	6	9	12	15
4	8	12	16	20
5	10	15	20	25

Practical Example: Calculator#

#include <stdio.h>

int main() {
    int choice;
    double num1, num2, result;

    do {
        printf("\n=== Simple Calculator ===\n");
        printf("1. Addition\n");
        printf("2. Subtraction\n");
        printf("3. Multiplication\n");
        printf("4. Division\n");
        printf("5. Exit\n");
        printf("Enter choice (1-5): ");
        scanf("%d", &choice);

        if (choice >= 1 && choice <= 4) {
            printf("Enter first number: ");
            scanf("%lf", &num1);
            printf("Enter second number: ");
            scanf("%lf", &num2);

            switch (choice) {
                case 1:
                    result = num1 + num2;
                    printf("Result: %.2f\n", result);
                    break;
                case 2:
                    result = num1 - num2;
                    printf("Result: %.2f\n", result);
                    break;
                case 3:
                    result = num1 * num2;
                    printf("Result: %.2f\n", result);
                    break;
                case 4:
                    if (num2 != 0) {
                        result = num1 / num2;
                        printf("Result: %.2f\n", result);
                    } else {
                        printf("Error: Division by zero!\n");
                    }
                    break;
            }
        } else if (choice != 5) {
            printf("Invalid choice!\n");
        }

    } while (choice != 5);

    printf("Thank you for using the calculator!\n");
    return 0;
}

Practice Exercises#

Exercise 1: Pattern Printing#

Print these patterns:

  1. Right triangle: *, **, ***, etc.
  2. Pyramid: *, ***, *****, etc.

Exercise 2: Number Analysis#

Write a program that:

  • Reads 5 numbers
  • Counts how many are positive/negative/zero
  • Displays the statistics

Exercise 3: Game Guessing#

Write a number guessing game:

  • Computer has a number (hardcode it first)
  • User guesses until correct
  • Tell if guess is too high/too low
  • Count attempts

Summary#

✅ Learned if, else-if, and else statements
✅ Mastered switch-case statements
✅ Understood for loops
✅ Used while and do-while loops
✅ Applied break and continue
✅ Created nested loops
✅ Built complete interactive programs

Key Points to Remember#

  1. Always use == for comparison
  2. Remember break in switch statements
  3. Initialize counter before while/do-while
  4. Use for loops when iteration count is known
  5. Use while/do-while for unknown iterations
  6. Nested loops can create complex patterns
  7. break exits loops; continue skips to next iteration

Next Steps#

Tomorrow we’ll learn about functions - how to write reusable, modular code!

→ Continue to Day 6

← Back to Day 4