⬅ Previous Next ➡

Control Flow in C

Control Flow in C
  • Control Flow decides the order in which statements execute in a C program.
  • C supports decision making (if, if-else, nested if, switch) and looping (for, while, do-while).
  • Jump statements change the normal flow: break, continue, goto, return.

1) if Statement

  • Executes a block only when the condition is true.
#include <stdio.h>

int main() {
    int marks = 75;

    if (marks >= 40) {
        printf("Result: Pass\n");
    }

    return 0;
}

2) if-else Statement

  • Runs if block when condition is true, otherwise runs else block.
#include <stdio.h>

int main() {
    int marks = 35;

    if (marks >= 40) {
        printf("Result: Pass\n");
    } else {
        printf("Result: Fail\n");
    }

    return 0;
}

3) Nested if

  • An if inside another if for multiple conditions.
#include <stdio.h>

int main() {
    int marks = 86;

    if (marks >= 40) {
        if (marks >= 75) {
            printf("Grade: Distinction\n");
        } else {
            printf("Grade: Pass\n");
        }
    } else {
        printf("Grade: Fail\n");
    }

    return 0;
}

4) switch Statement

  • Used when checking one variable against multiple cases.
  • break prevents fall-through to next case.
#include <stdio.h>

int main() {
    int choice = 2;

    switch (choice) {
        case 1:
            printf("Menu: View Profile\n");
            break;
        case 2:
            printf("Menu: Start Test\n");
            break;
        case 3:
            printf("Menu: View Result\n");
            break;
        default:
            printf("Invalid Option\n");
    }

    return 0;
}

5) for Loop

  • Best when number of iterations is known.
  • Syntax: for(initialization; condition; update)
#include <stdio.h>

int main() {
    int i;

    for (i = 1; i  0) {
        printf("Attempts left: %d\n", n);
        n--;
    }

    return 0;
}

7) do-while Loop

  • Executes at least once because condition is checked after the loop body.
#include <stdio.h>

int main() {
    int i = 1;

    do {
        printf("Run: %d\n", i);
        i++;
    } while (i