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
4The 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
5The value 3 is not printed because the continue statement skips the Console.WriteLine(i) for that iteration.
Challenge
EasyWrite a method called ProcessNumbers that takes an array of integers as a parameter. The method should:
- Print all numbers in the array
- Skip printing any negative numbers (use
continue) - Stop processing if it encounters a number greater than 100 (use
break) - Return the sum of all numbers that were printed
Cheat sheet
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);
}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);
}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)
{
// Create a sample array for immediate testing
int[] numbers = { 5, -3, 10, 15, -7, 105, 20 };
int sum = ProcessNumbers(numbers);
Console.WriteLine("Sum: " + sum);
// Also try with user input if provided
try
{
string input = Console.ReadLine();
if (!string.IsNullOrEmpty(input))
{
string[] parts = input.Split(',');
int[] inputNumbers = new int[parts.Length];
for (int i = 0; i < parts.Length; i++)
{
inputNumbers[i] = int.Parse(parts[i].Trim());
}
int inputSum = ProcessNumbers(inputNumbers);
Console.WriteLine("Input Sum: " + inputSum);
}
}
catch (Exception)
{
// If there's an error with input, just continue with the sample result
}
}
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Multi-dimensional Arrays
2D Arrays BasicsDeclaring and Initializing 2DAccessing 2D Array ElementsNested Loops with 2D ArraysJagged ArraysCommon Matrix OperationsRecap - Multi-dimensional4Flow Control Techniques
Early ReturnsGuard ClausesJump Statements (goto)Break and ContinueFlatten Nested Conditionals7Logical Operators Advanced
Short-Circuit EvaluationConditional Logical OperatorsOperator PrecedenceRecap - Advanced Operators2Advanced Decision Making
Multiple ConditionsComplex Boolean LogicIf vs. Switch ComparisonNested Switch StatementsRecap - Advanced Decisions5Exception Handling
Try-Catch BasicsException TypesMultiple Catch BlocksWorking with FilesFinally BlockUsing vs. Try-FinallyCustom ExceptionsRecap - Error Handling3Loop Enhancements
Loop PerformanceIterating ComplexEach Loop TypeRefactoring LoopsRecap - Optimized Loops6Null Handling
Null Reference BasicsNullable Value TypesNull Checking PatternsDefensive ProgrammingRecap - Null Safety