Coming Soon

This lesson is currently being developed

Control flow introduction

Learn to control the execution path of your programs.

Control Flow
Chapter
Beginner
Difficulty
30min
Estimated Time

What to Expect

Comprehensive explanations with practical examples

Interactive coding exercises to practice concepts

Knowledge quiz to test your understanding

Step-by-step guidance for beginners

Development Status

In Progress

Content is being carefully crafted to provide the best learning experience

Preview

Early Preview Content

This content is still being developed and may change before publication.

8.1 — Control flow introduction

In this lesson, you'll learn about control flow - the order in which statements in your program are executed, and how you can control that order.

What is control flow?

Control flow (also called flow of control) refers to the order in which individual statements, instructions, or function calls are executed in a program.

By default, C++ programs execute statements sequentially from top to bottom:

#include <iostream>

int main()
{
    std::cout << "Statement 1\n";   // Executes first
    std::cout << "Statement 2\n";   // Executes second
    std::cout << "Statement 3\n";   // Executes third
    
    return 0;  // Executes last
}

Output:

Statement 1
Statement 2
Statement 3

However, sequential execution is often not enough. Real programs need to:

  • Make decisions (execute different code based on conditions)
  • Repeat actions (execute the same code multiple times)
  • Jump to different parts of the program

Types of control flow statements

C++ provides several types of control flow statements:

1. Sequential flow (default)

Statements execute one after another in order.

2. Selection statements (conditional flow)

Execute different code based on conditions:

  • if statements - Execute code if a condition is true
  • else statements - Execute alternative code when if condition is false
  • switch statements - Select from multiple options based on a value

3. Iteration statements (loops)

Repeat code multiple times:

  • while loops - Repeat while a condition is true
  • do-while loops - Repeat at least once, then while condition is true
  • for loops - Repeat a specific number of times or over a range

4. Jump statements

Transfer control to another part of the program:

  • break - Exit from a loop or switch
  • continue - Skip to next iteration of a loop
  • return - Exit from a function
  • goto - Jump to a labeled statement (rarely used)

Why control flow matters

Control flow allows programs to be:

1. Responsive - React to user input and different conditions

#include <iostream>

int main()
{
    int age;
    std::cout << "Enter your age: ";
    std::cin >> age;
    
    if (age >= 18)
        std::cout << "You can vote!\n";
    else
        std::cout << "You're too young to vote.\n";
    
    return 0;
}

2. Efficient - Avoid repeating code

#include <iostream>

int main()
{
    // Without loops (inefficient):
    std::cout << "Hello\n";
    std::cout << "Hello\n";
    std::cout << "Hello\n";
    std::cout << "Hello\n";
    std::cout << "Hello\n";
    
    // With loops (efficient):
    for (int i = 0; i < 5; ++i)
    {
        std::cout << "Hello\n";
    }
    
    return 0;
}

3. Intelligent - Make decisions based on data

#include <iostream>

int main()
{
    double temperature;
    std::cout << "Enter temperature in Celsius: ";
    std::cin >> temperature;
    
    if (temperature > 35)
        std::cout << "It's hot today!\n";
    else if (temperature > 20)
        std::cout << "Nice weather!\n";
    else if (temperature > 0)
        std::cout << "It's cool today.\n";
    else
        std::cout << "It's freezing!\n";
    
    return 0;
}

Program flow visualization

Let's trace through a simple program to see how control flow works:

#include <iostream>

int main()
{
    int x = 5;                    // 1. Execute first
    
    std::cout << "x is: " << x;   // 2. Execute second
    
    if (x > 3)                    // 3. Evaluate condition
    {
        std::cout << " (greater than 3)";  // 4. Execute if true
    }
    
    std::cout << std::endl;       // 5. Always execute
    
    return 0;                     // 6. Execute last
}

Flow: 1 → 2 → 3 → 4 (condition is true) → 5 → 6

Output:

x is: 5 (greater than 3)

If we changed x = 2, the flow would be: 1 → 2 → 3 → 5 (skip 4) → 6

Compound statements (blocks)

Often, you want to execute multiple statements as a group. Use blocks (compound statements) with curly braces {}:

#include <iostream>

int main()
{
    int score = 85;
    
    if (score >= 80)
    {
        // This is a block - multiple statements treated as one
        std::cout << "Excellent work!\n";
        std::cout << "You got an A!\n";
        std::cout << "Keep it up!\n";
    }
    
    std::cout << "Program finished.\n";
    
    return 0;
}

Output:

Excellent work!
You got an A!
Keep it up!
Program finished.

Nested control flow

Control flow statements can be nested (placed inside each other):

#include <iostream>

int main()
{
    int age, hasLicense;
    
    std::cout << "Enter your age: ";
    std::cin >> age;
    
    if (age >= 16)  // Outer condition
    {
        std::cout << "Do you have a driver's license? (1 for yes, 0 for no): ";
        std::cin >> hasLicense;
        
        if (hasLicense)  // Nested condition
        {
            std::cout << "You can drive!\n";
        }
        else
        {
            std::cout << "You need to get a license first.\n";
        }
    }
    else  // age < 16
    {
        std::cout << "You're too young to drive.\n";
    }
    
    return 0;
}

This program has nested if statements - the inner if/else is only evaluated if the outer condition (age >= 16) is true.

Common control flow patterns

Pattern 1: Input validation

#include <iostream>

int main()
{
    int number;
    
    std::cout << "Enter a positive number: ";
    std::cin >> number;
    
    if (number > 0)
    {
        std::cout << "Thank you! You entered: " << number << std::endl;
    }
    else
    {
        std::cout << "Error: Please enter a positive number.\n";
    }
    
    return 0;
}

Pattern 2: Menu selection

#include <iostream>

int main()
{
    int choice;
    
    std::cout << "Menu:\n";
    std::cout << "1. New Game\n";
    std::cout << "2. Load Game\n";
    std::cout << "3. Settings\n";
    std::cout << "4. Exit\n";
    std::cout << "Choose an option: ";
    std::cin >> choice;
    
    if (choice == 1)
        std::cout << "Starting new game...\n";
    else if (choice == 2)
        std::cout << "Loading saved game...\n";
    else if (choice == 3)
        std::cout << "Opening settings...\n";
    else if (choice == 4)
        std::cout << "Goodbye!\n";
    else
        std::cout << "Invalid choice!\n";
    
    return 0;
}

Pattern 3: Range checking

#include <iostream>

int main()
{
    int grade;
    
    std::cout << "Enter your exam grade (0-100): ";
    std::cin >> grade;
    
    if (grade >= 90)
        std::cout << "Grade: A\n";
    else if (grade >= 80)
        std::cout << "Grade: B\n";
    else if (grade >= 70)
        std::cout << "Grade: C\n";
    else if (grade >= 60)
        std::cout << "Grade: D\n";
    else if (grade >= 0)
        std::cout << "Grade: F\n";
    else
        std::cout << "Invalid grade!\n";
    
    return 0;
}

Best practices for control flow

  1. Use meaningful conditions: Make your conditions clear and readable

    // Good
    if (age >= VOTING_AGE)
    
    // Less clear
    if (age >= 18)
    
  2. Keep nesting shallow: Too many nested levels make code hard to read

    // Avoid deep nesting like this:
    if (condition1)
    {
        if (condition2)
        {
            if (condition3)
            {
                // Too deep!
            }
        }
    }
    
  3. Use blocks consistently: Always use braces, even for single statements

    // Good - clear and consistent
    if (temperature > 30)
    {
        std::cout << "It's hot!\n";
    }
    
    // Risky - easy to make mistakes when adding code
    if (temperature > 30)
        std::cout << "It's hot!\n";
    

Summary

Control flow determines the order in which your program executes statements:

  • Sequential flow: Default top-to-bottom execution
  • Selection statements: Make decisions with if/else and switch
  • Iteration statements: Repeat code with loops
  • Jump statements: Transfer control with break, continue, return

Good control flow makes programs:

  • Responsive to different inputs and conditions
  • Efficient by avoiding code repetition
  • Intelligent by making decisions based on data

In the following lessons, you'll learn about each type of control flow statement in detail, starting with if statements and conditional logic.

Quiz

  1. What is control flow?
  2. What are the four main categories of control flow statements?
  3. What is the default control flow in C++?
  4. Why do we need control flow statements instead of just sequential execution?
  5. What is a compound statement (block)?

Practice exercises

Try creating programs that use different control flow concepts:

  1. Write a program that asks for a number and tells the user if it's positive, negative, or zero
  2. Create a simple calculator that asks for two numbers and an operation (+, -, *, /) and performs the calculation
  3. Make a program that converts grades (0-100) to letter grades (A, B, C, D, F)
  4. Design a program that asks the user's age and determines what activities they can do (vote, drive, drink, etc.)

Continue Learning

Explore other available lessons while this one is being prepared.

View Course

Explore More Courses

Discover other available courses while this lesson is being prepared.

Browse Courses

Lesson Discussion

Share your thoughts and questions

💬

No comments yet. Be the first to share your thoughts!

Sign in to join the discussion