Menu
Coddy logo textTech

Break and Continue

Part of the Logic & Flow section of Coddy's C# journey — lesson 21 of 66.

In C#, break and continue are statements that give you greater control over loop execution.

The break statement

The break statement immediately exits a loop:

for (int i = 1; i <= 10; i++)
{
    if (i == 5)
    {
        break; // Exit the loop when i equals 5
    }
    Console.WriteLine(i);
}

After executing the above code, the output will be:

1
2
3
4

The loop stops as soon as i equals 5, and execution continues with the code after the loop.

The continue statement

The continue statement skips the rest of the current iteration and jumps to the next iteration:

for (int i = 1; i <= 5; i++)
{
    if (i == 3)
    {
        continue; // Skip the rest of this iteration
    }
    Console.WriteLine(i);
}

After executing the above code, the output will be:

1
2
4
5

The value 3 is not printed because the continue statement skips the Console.WriteLine(i) for that iteration.

challenge icon

Challenge

Easy

Write a method called ProcessNumbers that takes an array of integers as a parameter. The method should:

  1. Print all numbers in the array
  2. Skip printing any negative numbers (use continue)
  3. Stop processing if it encounters a number greater than 100 (use break)
  4. Return the sum of all numbers that were printed

Try it yourself

using System;

public class Program
{
    public static int ProcessNumbers(int[] numbers)
    {
        // Write your code here
        return 0;
    }
    
    public static void Main(string[] args)
    {
        // Read input from the user
        string input = Console.ReadLine();
        int[] numbers;
        
        if (string.IsNullOrEmpty(input))
        {
            // Sample array for testing
            numbers = new int[] { 5, -3, 10, 15, -7, 105, 20 };
        }
        else
        {
            string[] parts = input.Split(',');
            numbers = new int[parts.Length];
            for (int i = 0; i < parts.Length; i++)
            {
                numbers[i] = int.Parse(parts[i].Trim());
            }
        }
        
        int sum = ProcessNumbers(numbers);
        Console.WriteLine("Sum: " + sum);
    }
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Logic & Flow