Coming Soon

This lesson is currently being developed

Break and continue

Control loop execution with break and continue statements.

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.11 — Break and continue

In this lesson, you'll learn about break and continue statements, which give you precise control over loop execution. These statements allow you to exit loops early or skip to the next iteration, making your loops more flexible and efficient.

What are break and continue?

Break and continue are jump statements that alter the normal flow of loops:

  • break: Immediately exits the current loop completely
  • continue: Skips the rest of the current iteration and jumps to the next iteration

Think of break as an "emergency exit" and continue as a "skip ahead" button.

The break statement

The break statement immediately terminates the loop and transfers control to the statement after the loop.

Basic break example

#include <iostream>

int main()
{
    std::cout << "Counting with break:\n";
    
    for (int i = 1; i <= 10; ++i)
    {
        if (i == 6)
        {
            break;  // Exit the loop when i equals 6
        }
        std::cout << i << " ";
    }
    
    std::cout << "\nLoop finished early!" << std::endl;
    
    return 0;
}

Output:

Counting with break:
1 2 3 4 5 
Loop finished early!

The loop stops completely when i reaches 6, and control jumps to the statement after the loop.

Break with while loops

#include <iostream>

int main()
{
    std::cout << "Enter numbers (0 to stop): ";
    
    int number;
    int sum = 0;
    
    while (true)  // Infinite loop
    {
        std::cin >> number;
        
        if (number == 0)
        {
            break;  // Exit when user enters 0
        }
        
        sum += number;
        std::cout << "Current sum: " << sum << std::endl;
    }
    
    std::cout << "Final sum: " << sum << std::endl;
    
    return 0;
}

Sample Output:

Enter numbers (0 to stop): 10
Current sum: 10
5
Current sum: 15
3
Current sum: 18
0
Final sum: 18

Practical break example: Finding a value

#include <iostream>

int main()
{
    int targetNumber;
    std::cout << "Enter the number to search for: ";
    std::cin >> targetNumber;
    
    int numbers[] = {10, 25, 3, 47, 91, 13, 8};
    int arraySize = 7;
    bool found = false;
    int position = -1;
    
    for (int i = 0; i < arraySize; ++i)
    {
        if (numbers[i] == targetNumber)
        {
            found = true;
            position = i;
            break;  // Found it, no need to continue searching
        }
    }
    
    if (found)
    {
        std::cout << "Found " << targetNumber << " at position " << position << std::endl;
    }
    else
    {
        std::cout << "Number " << targetNumber << " not found." << std::endl;
    }
    
    return 0;
}

Sample Output:

Enter the number to search for: 47
Found 47 at position 3

The continue statement

The continue statement skips the remaining code in the current iteration and moves to the next iteration of the loop.

Basic continue example

#include <iostream>

int main()
{
    std::cout << "Odd numbers from 1 to 10:\n";
    
    for (int i = 1; i <= 10; ++i)
    {
        if (i % 2 == 0)  // If even number
        {
            continue;  // Skip the rest of this iteration
        }
        
        std::cout << i << " ";  // This only executes for odd numbers
    }
    
    std::cout << std::endl;
    
    return 0;
}

Output:

Odd numbers from 1 to 10:
1 3 5 7 9 

Continue with while loops

#include <iostream>

int main()
{
    std::cout << "Processing numbers 1-10, skipping multiples of 3:\n";
    
    int i = 0;
    while (i < 10)
    {
        ++i;  // Important: increment before continue check
        
        if (i % 3 == 0)
        {
            continue;  // Skip multiples of 3
        }
        
        std::cout << "Processing: " << i << std::endl;
    }
    
    return 0;
}

Output:

Processing numbers 1-10, skipping multiples of 3:
Processing: 1
Processing: 2
Processing: 4
Processing: 5
Processing: 7
Processing: 8
Processing: 10

Practical continue example: Input validation

#include <iostream>

int main()
{
    std::cout << "Enter 5 positive numbers:\n";
    
    int validNumbers = 0;
    double sum = 0.0;
    
    while (validNumbers < 5)
    {
        double number;
        std::cout << "Enter number " << (validNumbers + 1) << ": ";
        std::cin >> number;
        
        if (number <= 0)
        {
            std::cout << "Please enter a positive number.\n";
            continue;  // Skip this iteration, don't count this input
        }
        
        // Only reached if number is positive
        sum += number;
        ++validNumbers;
    }
    
    double average = sum / 5;
    std::cout << "Sum: " << sum << std::endl;
    std::cout << "Average: " << average << std::endl;
    
    return 0;
}

Sample Output:

Enter 5 positive numbers:
Enter number 1: 10
Enter number 2: -5
Please enter a positive number.
Enter number 2: 15
Enter number 3: 8
Enter number 4: 0
Please enter a positive number.
Enter number 4: 12
Enter number 5: 20
Sum: 65
Average: 13

Break vs continue comparison

Visual comparison

#include <iostream>

int main()
{
    std::cout << "Using break:\n";
    for (int i = 1; i <= 8; ++i)
    {
        if (i == 5)
        {
            break;  // Exits loop completely
        }
        std::cout << i << " ";
    }
    std::cout << "\n\n";
    
    std::cout << "Using continue:\n";
    for (int i = 1; i <= 8; ++i)
    {
        if (i == 5)
        {
            continue;  // Skips only this iteration
        }
        std::cout << i << " ";
    }
    std::cout << std::endl;
    
    return 0;
}

Output:

Using break:
1 2 3 4 

Using continue:
1 2 3 4 6 7 8 

Nested loops and break/continue

Break and continue only affect the innermost loop they're in:

Break in nested loops

#include <iostream>

int main()
{
    std::cout << "Break in nested loop:\n";
    
    for (int i = 1; i <= 3; ++i)
    {
        std::cout << "Outer loop i = " << i << "\n";
        
        for (int j = 1; j <= 5; ++j)
        {
            if (j == 3)
            {
                break;  // Only exits inner loop
            }
            std::cout << "  Inner loop j = " << j << "\n";
        }
        
        std::cout << "  Back in outer loop\n";
    }
    
    return 0;
}

Output:

Break in nested loop:
Outer loop i = 1
  Inner loop j = 1
  Inner loop j = 2
  Back in outer loop
Outer loop i = 2
  Inner loop j = 1
  Inner loop j = 2
  Back in outer loop
Outer loop i = 3
  Inner loop j = 1
  Inner loop j = 2
  Back in outer loop

Continue in nested loops

#include <iostream>

int main()
{
    std::cout << "Continue in nested loop:\n";
    
    for (int i = 1; i <= 3; ++i)
    {
        std::cout << "Outer loop i = " << i << "\n";
        
        for (int j = 1; j <= 5; ++j)
        {
            if (j == 3)
            {
                continue;  // Only skips current inner loop iteration
            }
            std::cout << "  Inner loop j = " << j << "\n";
        }
    }
    
    return 0;
}

Output:

Continue in nested loop:
Outer loop i = 1
  Inner loop j = 1
  Inner loop j = 2
  Inner loop j = 4
  Inner loop j = 5
Outer loop i = 2
  Inner loop j = 1
  Inner loop j = 2
  Inner loop j = 4
  Inner loop j = 5
Outer loop i = 3
  Inner loop j = 1
  Inner loop j = 2
  Inner loop j = 4
  Inner loop j = 5

Practical examples

Example 1: Simple calculator with menu

#include <iostream>

int main()
{
    double num1, num2;
    char operation;
    char continueChoice;
    
    do
    {
        std::cout << "\n=== Simple Calculator ===\n";
        std::cout << "Enter first number: ";
        std::cin >> num1;
        
        std::cout << "Enter operation (+, -, *, /): ";
        std::cin >> operation;
        
        if (operation != '+' && operation != '-' && 
            operation != '*' && operation != '/')
        {
            std::cout << "Invalid operation!\n";
            continue;  // Skip to next iteration of do-while
        }
        
        std::cout << "Enter second number: ";
        std::cin >> num2;
        
        if (operation == '/' && num2 == 0)
        {
            std::cout << "Error: Division by zero!\n";
            continue;  // Skip to next iteration
        }
        
        double result;
        switch (operation)
        {
            case '+': result = num1 + num2; break;
            case '-': result = num1 - num2; break;
            case '*': result = num1 * num2; break;
            case '/': result = num1 / num2; break;
        }
        
        std::cout << num1 << " " << operation << " " << num2 << " = " << result << std::endl;
        
        std::cout << "Continue? (y/n): ";
        std::cin >> continueChoice;
        
        if (continueChoice == 'n' || continueChoice == 'N')
        {
            break;  // Exit the calculator
        }
        
    } while (true);
    
    std::cout << "Calculator closed. Goodbye!" << std::endl;
    
    return 0;
}

Example 2: Password validation

#include <iostream>
#include <string>

int main()
{
    std::string password;
    const int MAX_ATTEMPTS = 3;
    int attempts = 0;
    
    std::cout << "Password must be at least 8 characters long\n";
    
    while (attempts < MAX_ATTEMPTS)
    {
        std::cout << "Enter password: ";
        std::cin >> password;
        ++attempts;
        
        if (password.length() < 8)
        {
            std::cout << "Password too short! Try again.\n";
            std::cout << "Attempts remaining: " << (MAX_ATTEMPTS - attempts) << "\n\n";
            continue;  // Try again
        }
        
        // Password is valid
        std::cout << "Password accepted!" << std::endl;
        break;  // Exit the loop
    }
    
    if (attempts >= MAX_ATTEMPTS)
    {
        std::cout << "Too many failed attempts. Access denied." << std::endl;
    }
    
    return 0;
}

Example 3: Number guessing game

#include <iostream>
#include <cstdlib>
#include <ctime>

int main()
{
    // Seed random number generator
    std::srand(std::time(nullptr));
    
    int secretNumber = std::rand() % 100 + 1;  // 1-100
    int guess;
    int attempts = 0;
    const int MAX_ATTEMPTS = 7;
    
    std::cout << "Guess the number (1-100)!\n";
    std::cout << "You have " << MAX_ATTEMPTS << " attempts.\n\n";
    
    while (attempts < MAX_ATTEMPTS)
    {
        std::cout << "Attempt " << (attempts + 1) << ": Enter your guess: ";
        std::cin >> guess;
        ++attempts;
        
        if (guess < 1 || guess > 100)
        {
            std::cout << "Please enter a number between 1 and 100.\n";
            --attempts;  // Don't count invalid guesses
            continue;
        }
        
        if (guess == secretNumber)
        {
            std::cout << "Congratulations! You guessed it in " << attempts << " attempts!\n";
            break;  // Game won, exit loop
        }
        else if (guess < secretNumber)
        {
            std::cout << "Too low! ";
        }
        else
        {
            std::cout << "Too high! ";
        }
        
        std::cout << "Try again.\n\n";
    }
    
    if (attempts >= MAX_ATTEMPTS && guess != secretNumber)
    {
        std::cout << "Game over! The number was " << secretNumber << std::endl;
    }
    
    return 0;
}

Common mistakes and best practices

Mistake 1: Infinite loops with continue

// WRONG - infinite loop
int i = 0;
while (i < 5)
{
    if (i == 2)
    {
        continue;  // i never gets incremented when i == 2
    }
    ++i;
}

// CORRECT - increment before continue
int i = 0;
while (i < 5)
{
    ++i;  // Increment first
    if (i == 2)
    {
        continue;  // Now it's safe to continue
    }
    // Other processing
}

Mistake 2: Using break in switch vs loops

// Remember: break in switch is different from break in loops
int value = 2;

switch (value)
{
    case 1:
        std::cout << "One" << std::endl;
        break;  // Exits switch, not any containing loop
    case 2:
        std::cout << "Two" << std::endl;
        break;  // Exits switch, not any containing loop
}

Best practice 1: Keep break/continue conditions simple

// Good - clear condition
for (int i = 0; i < items; ++i)
{
    if (data[i] == target)
    {
        break;
    }
}

// Avoid - complex condition
for (int i = 0; i < items; ++i)
{
    if (data[i] == target && isValid(i) && checkPermissions() && otherComplexCheck())
    {
        break;
    }
}

Best practice 2: Use meaningful variable names

// Good - clear intent
bool found = false;
for (int index = 0; index < size && !found; ++index)
{
    if (array[index] == searchValue)
    {
        found = true;
        break;
    }
}

// Less clear
for (int i = 0; i < n; ++i)
{
    if (arr[i] == val)
    {
        break;
    }
}

When to use break and continue

Use break when:

  • Searching for a specific value (found it, stop looking)
  • Error conditions that require immediate loop exit
  • User input indicates they want to quit
  • Maximum attempts reached
  • Implementing state machines or menu systems

Use continue when:

  • Filtering data (skip invalid entries)
  • Input validation (retry on invalid input)
  • Processing only certain elements
  • Skipping expensive operations for some cases

Alternative approaches

Sometimes break and continue can be replaced with better loop conditions:

// Using break
bool found = false;
for (int i = 0; i < size; ++i)
{
    if (array[i] == target)
    {
        found = true;
        break;
    }
}

// Alternative: better loop condition
bool found = false;
for (int i = 0; i < size && !found; ++i)
{
    found = (array[i] == target);
}

Summary

Break and continue statements provide precise control over loop execution:

Break statement:

  • Immediately exits the current loop completely
  • Transfers control to the first statement after the loop
  • Only affects the innermost loop in nested structures
  • Perfect for search operations and early exit conditions

Continue statement:

  • Skips the rest of the current iteration
  • Jumps to the next iteration of the loop
  • Only affects the innermost loop in nested structures
  • Ideal for filtering and input validation

Key points:

  • Both only affect the innermost loop they're in
  • Use sparingly and with clear intent
  • Be careful with continue in while loops (ensure loop variables are updated)
  • Consider alternative loop conditions when appropriate
  • Make conditions simple and readable

Common uses:

  • Break: searching, error handling, user-initiated exits
  • Continue: filtering, validation, skipping processing

Break and continue make loops more flexible and can make your code more efficient by avoiding unnecessary work.

Quiz

  1. What's the difference between break and continue?
  2. In nested loops, which loop does break affect?
  3. What's a common mistake when using continue with while loops?
  4. When would you use break in a search algorithm?
  5. How can continue be useful for input validation?

Practice exercises

  1. Even number printer: Write a program that prints numbers 1-20, but uses continue to skip odd numbers.

  2. Prime number finder: Create a program that finds and prints the first 10 prime numbers. Use break to exit the inner divisibility test loop early when a divisor is found.

  3. Menu-driven program: Write a simple menu system that keeps running until the user chooses to exit. Use continue for invalid menu choices and break to exit the program.

  4. String validator: Create a program that reads strings from the user and only accepts those that meet certain criteria (e.g., minimum length, contains certain characters). Use continue to reject invalid strings and break when enough valid strings are collected.

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