04

Module 4: Control Flow

Chapter 4 • Beginner

40 min

Control Flow

Control flow statements allow your program to make decisions and repeat code. They are essential for creating dynamic, interactive programs.

What is Control Flow?

Control flow determines the order in which statements are executed in your program. It includes:

  • Conditional statements: Execute code based on conditions (if/else, switch)
  • Loops: Repeat code multiple times (for, while, do-while)

Conditional Statements

1. If Statement

Execute code only if a condition is true.

Syntax:

cpp.js
if (condition) {
    // code to execute if condition is true
}

Example:

cpp.js
int age = 20;
if (age >= 18) {
    cout << "You are an adult" << endl;
}

2. If-Else Statement

Execute one block if condition is true, another if false.

Syntax:

cpp.js
if (condition) {
    // code if true
} else {
    // code if false
}

Example:

cpp.js
int score = 85;
if (score >= 60) {
    cout << "Passed" << endl;
} else {
    cout << "Failed" << endl;
}

3. If-Else If-Else Statement

Handle multiple conditions.

Syntax:

cpp.js
if (condition1) {
    // code for condition1
} else if (condition2) {
    // code for condition2
} else if (condition3) {
    // code for condition3
} else {
    // code if none are true
}

Example:

cpp.js
int score = 85;
if (score >= 90) {
    cout << "Grade: A" << endl;
} else if (score >= 80) {
    cout << "Grade: B" << endl;
} else if (score >= 70) {
    cout << "Grade: C" << endl;
} else if (score >= 60) {
    cout << "Grade: D" << endl;
} else {
    cout << "Grade: F" << endl;
}

4. Nested If Statements

If statements inside other if statements.

Example:

cpp.js
int age = 20;
bool hasLicense = true;

if (age >= 18) {
    if (hasLicense) {
        cout << "You can drive" << endl;
    } else {
        cout << "You need a license" << endl;
    }
} else {
    cout << "You are too young" << endl;
}

5. Switch Statement

Efficient way to handle multiple conditions based on a single variable.

Syntax:

cpp.js
switch (variable) {
    case value1:
        // code
        break;
    case value2:
        // code
        break;
    default:
        // code if no case matches
}

Example:

cpp.js
int day = 3;
switch (day) {
    case 1:
        cout << "Monday" << endl;
        break;
    case 2:
        cout << "Tuesday" << endl;
        break;
    case 3:
        cout << "Wednesday" << endl;
        break;
    default:
        cout << "Other day" << endl;
}

Important Notes:

  • Use break to exit switch (otherwise execution continues to next case)
  • default handles unmatched values
  • Switch only works with integers, characters, and enums (not strings in older C++)

Loops

Loops allow you to repeat code multiple times.

1. For Loop

Execute code a specific number of times.

Syntax:

cpp.js
for (initialization; condition; increment) {
    // code to repeat
}

Example:

cpp.js
for (int i = 0; i < 5; i++) {
    cout << i << " ";
}
// Output: 0 1 2 3 4

Parts:

  • Initialization: Executes once at start
  • Condition: Checked before each iteration
  • Increment: Executes after each iteration

Common Patterns:

cpp.js
// Count from 0 to 9
for (int i = 0; i < 10; i++) { }

// Count from 1 to 10
for (int i = 1; i <= 10; i++) { }

// Count backwards
for (int i = 10; i > 0; i--) { }

// Count by 2s
for (int i = 0; i < 10; i += 2) { }

2. While Loop

Repeat code while condition is true.

Syntax:

cpp.js
while (condition) {
    // code to repeat
}

Example:

cpp.js
int count = 0;
while (count < 5) {
    cout << count << " ";
    count++;
}
// Output: 0 1 2 3 4

Important: Make sure condition eventually becomes false, or you'll have an infinite loop!

3. Do-While Loop

Execute code at least once, then repeat while condition is true.

Syntax:

cpp.js
do {
    // code to repeat
} while (condition);

Example:

cpp.js
int number;
do {
    cout << "Enter positive number: ";
    cin >> number;
} while (number <= 0);

Difference from while: Do-while always executes at least once, even if condition is false initially.

4. Nested Loops

Loops inside other loops.

Example:

cpp.js
for (int i = 1; i <= 3; i++) {
    for (int j = 1; j <= 3; j++) {
        cout << i << "," << j << " ";
    }
    cout << endl;
}
// Output:
// 1,1 1,2 1,3
// 2,1 2,2 2,3
// 3,1 3,2 3,3

Loop Control Statements

Break Statement

Exit the loop immediately.

Example:

cpp.js
for (int i = 0; i < 10; i++) {
    if (i == 5) {
        break;  // Exit loop when i is 5
    }
    cout << i << " ";
}
// Output: 0 1 2 3 4

Continue Statement

Skip to next iteration of the loop.

Example:

cpp.js
for (int i = 0; i < 10; i++) {
    if (i % 2 == 0) {
        continue;  // Skip even numbers
    }
    cout << i << " ";
}
// Output: 1 3 5 7 9

Range-Based For Loop (C++11)

Iterate over elements in a container (arrays, vectors, etc.).

Syntax:

cpp.js
for (type element : container) {
    // code
}

Example:

cpp.js
int arr[] = {1, 2, 3, 4, 5};
for (int num : arr) {
    cout << num << " ";
}
// Output: 1 2 3 4 5

Common Patterns

Pattern 1: Sum of Numbers

cpp.js
int sum = 0;
for (int i = 1; i <= 100; i++) {
    sum += i;
}
cout << "Sum: " << sum << endl;

Pattern 2: Finding Maximum

cpp.js
int max = arr[0];
for (int i = 1; i < size; i++) {
    if (arr[i] > max) {
        max = arr[i];
    }
}

Pattern 3: Input Validation

cpp.js
int number;
do {
    cout << "Enter number (1-10): ";
    cin >> number;
} while (number < 1 || number > 10);

Best Practices

  1. Use meaningful variable names in loops (i, j are okay for simple loops)
  2. Initialize loop variables properly
  3. Ensure loop termination (avoid infinite loops)
  4. Use appropriate loop type:
  • for when you know number of iterations
  • while when condition is checked first
  • do-while when you need at least one execution
  1. Keep loop bodies simple - extract complex logic to functions
  2. Use `break` and `continue` sparingly - they can make code harder to read

Common Mistakes

  • ❌ Infinite loops (condition never becomes false)
  • ❌ Off-by-one errors (i <= 10 vs i < 10)
  • ❌ Forgetting break in switch statements
  • ❌ Modifying loop variable inside loop body incorrectly
  • ❌ Using = instead of == in conditions

Next Module

In Module 5, we'll learn about Functions - how to organize code into reusable blocks and make your programs more modular!

Hands-on Examples

If-Else Statements

#include <iostream>
using namespace std;

int main() {
    int score = 85;
    
    // Simple if
    if (score >= 60) {
        cout << "You passed!" << endl;
    }
    
    // If-else
    if (score >= 90) {
        cout << "Grade: A" << endl;
    } else if (score >= 80) {
        cout << "Grade: B" << endl;
    } else if (score >= 70) {
        cout << "Grade: C" << endl;
    } else if (score >= 60) {
        cout << "Grade: D" << endl;
    } else {
        cout << "Grade: F" << endl;
    }
    
    // Nested if
    int age = 20;
    bool hasLicense = true;
    if (age >= 18) {
        if (hasLicense) {
            cout << "You can drive" << endl;
        } else {
            cout << "Get a license first" << endl;
        }
    } else {
        cout << "Too young to drive" << endl;
    }
    
    return 0;
}

If-else statements allow your program to make decisions. The first condition that is true executes its block. If none are true, the else block executes. You can nest if statements for complex logic.