Control Structures (Lesson)

Control Structures: Decision Making

Control structures allow you to control the flow of execution based on specific conditions. Without these, programs would only run linearly from top to bottom.

7.1 Single Decision: if statement

The simplest form of control.

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

7.2 Two-way Decision: if-else

Executed when you have two possibilities.

if (num % 2 == 0) {
    printf("Even");
} else {
    printf("Odd");
}

7.3 Multi-way Decision: else-if Ladder

Used when there are multiple conditions to check sequentially.

if (marks >= 80) {
    printf("Grade: A");
} else if (marks >= 60) {
    printf("Grade: B");
} else if (marks >= 40) {
    printf("Grade: C");
} else {
    printf("Grade: F");
}

7.4 Nested if-else

Placing an if statement inside another if statement.

if (a > b) {
    if (a > c) {
        printf("A is greatest");
    }
}

7.5 The Multi-choice switch statement

An alternative to the else-if ladder when comparing a single variable against various fixed values.

Rules for switch:

  1. The expression must be an integer or character.
  2. case labels must be unique constants.
  3. Each case usually ends with a break to exit the switch.
  4. The default case is executed if no match is found.
switch (day) {
    case 1: printf("Monday"); break;
    case 2: printf("Tuesday"); break;
    case 3: printf("Wednesday"); break;
    default: printf("Invalid Day");
}

Example: Calculator using Switch

#include <stdio.h>

int main() {
    char op;
    double first, second;
    printf("Enter an operator (+, -, *, /): ");
    scanf("%c", &op);
    printf("Enter two operands: ");
    scanf("%lf %lf", &first, &second);

    switch (op) {
        case '+':
            printf("%.1lf + %.1lf = %.1lf", first, second, first + second);
            break;
        case '-':
            printf("%.1lf - %.1lf = %.1lf", first, second, first - second);
            break;
        case '*':
            printf("%.1lf * %.1lf = %.1lf", first, second, first * second);
            break;
        case '/':
            printf("%.1lf / %.1lf = %.1lf", first, second, first / second);
            break;
        default:
            printf("Error! operator is not correct");
    }
    return 0;
}

Refer to the Lecture Slides for visual flow diagrams of Switch and Ladder logic.

PREVIOUS
5. Writing a Program in C
NEXT
Loops