TutorialsCProgram Flow in C
Share:

Program Flow in C

intermediate

What You'll Learn

    Theory

    Controlling program flow is essential in any language. C provides control structures (if, else, switch), loops (for, while, do-while), and functions to organize and direct execution.

    Control Structures

    The if/else statement executes code based on a condition. C uses relational operators (==, !=, <, >, <=, >=) and logical operators (&&, ||, !). The switch statement efficiently selects among multiple discrete values.

    if (score >= 90) {
        printf("Grade: A");
    } else if (score >= 80) {
        printf("Grade: B");
    } else {
        printf("Grade: C");
    }

    Loops

    • for — iterate a known number of times: for(int i = 0; i < 10; i++)
    • while — repeat while a condition is true: while(count > 0)
    • do-while — execute body at least once: do { ... } while(condition)

    Functions

    Functions in C have a return type, a name, parameters, and a body. They enable code reuse, modularity, and abstraction. Function declarations (prototypes) inform the compiler about a function before its definition.

    Why this matters

    Control flow and functions are the core of every C program. Whether you're writing a simple calculator or an embedded system driver, mastering conditionals, loops, and function design is essential for writing correct, maintainable C code.

    What's next

    In the next lessons, you'll dive deeper into each topic with hands-on examples and exercises.

    Practical Examples

    Example: Program Flow with Loops and Functions
    c

    Exercises

    Sum of Even Numbers

    easy

    Write a C program that calculates the sum of all even numbers from 1 to 100 using a for loop. Print the result.

    Starter Code:

    #include <stdio.h>\n\nint main() {\n  int sum = 0;\n  // Your code here\n  return 0;\n}

    Expected Output:

    2550

    Mini Quiz

    Mini Quiz