2 min read

Control Flow

Control flow refers to the order in which the individual statements, instructions, or function calls of a program are executed. Without control flow, a program would simply run from top to bottom. Control flow structures allow for decision-making and repetition.

1. Conditionals

Conditionals allow the program to execute different code blocks based on whether a specific condition evaluates to true or false.

If / Else Statements

The most fundamental control structure.

  • JavaScript / C / Java:

    if (score > 50) {
        console.log("Pass");
    } else {
        console.log("Fail");
    }
  • Python:

    if score > 50:
        print("Pass")
    else:
        print("Fail")

Switch Statements

Used to select one of many code blocks to be executed. It is often cleaner than many if...else if statements.

  • JavaScript / Java:
    switch (day) {
        case 1:
            console.log("Monday");
            break;
        case 2:
            console.log("Tuesday");
            break;
        default:
            console.log("Unknown");
    }

2. Loops (Iteration)

Loops allow you to repeat a block of code multiple times.

For Loops

Used when you know exactly how many times you want to loop.

  • C-Style (Java, C++, JS):

    for (let i = 0; i < 5; i++) {
        console.log(i);
    }
  • Python:

    for i in range(5):
        print(i)

While Loops

Used when you want to loop as long as a condition is true.

  • General Syntax:
    while (isActive) {
        // do something
    }

3. Control Transfer Statements

  • Break: Terminates the current loop or switch statement immediately.
  • Continue: Skips the rest of the current loop iteration and jumps to the next one.
  • Return: Exits the current function and optionally returns a value.

programming/common-syntax