Break and Continue Statements
The break and continue statements give you control over loop execution. Use them to exit loops early or skip iterations.
The break Statement
break immediately exits the loop:
csharp1for (int i = 1; i <= 10; i++)2{3 if (i == 5)4 {5 break; // Exit the loop6 }7 Console.WriteLine(i);8}9Console.WriteLine("Done");
Output
112233445Done
The loop stops when i equals 5, and 5 is never printed.
break Use Cases
Search and Stop
csharp1int[] numbers = { 4, 8, 15, 16, 23, 42 };2int searchFor = 16;3int foundIndex = -1;45for (int i = 0; i < numbers.Length; i++)6{7 if (numbers[i] == searchFor)8 {9 foundIndex = i;10 break; // Found it, no need to continue11 }12}1314if (foundIndex >= 0)15{16 Console.WriteLine($"Found at index {foundIndex}");17}
User Quits
csharp1while (true)2{3 Console.Write("Enter command (q to quit): ");4 string input = Console.ReadLine() ?? "";56 if (input.ToLower() == "q")7 {8 break; // Exit the infinite loop9 }1011 Console.WriteLine($"Processing: {input}");12}13Console.WriteLine("Goodbye!");
First Match
csharp1string[] names = { "Alice", "Bob", "Charlie", "Diana" };2string firstWithA = "";34foreach (string name in names)5{6 if (name.StartsWith("A"))7 {8 firstWithA = name;9 break;10 }11}1213Console.WriteLine($"First name starting with A: {firstWithA}");
The continue Statement
continue skips the rest of the current iteration and moves to the next:
csharp1for (int i = 1; i <= 5; i++)2{3 if (i == 3)4 {5 continue; // Skip the rest of this iteration6 }7 Console.WriteLine(i);8}
Output
11223445
The number 3 is skipped.
continue Use Cases
Skip Invalid Items
csharp1string[] inputs = { "5", "abc", "10", "", "15" };2int sum = 0;34foreach (string input in inputs)5{6 if (!int.TryParse(input, out int number))7 {8 continue; // Skip non-numeric inputs9 }10 sum += number;11}1213Console.WriteLine($"Sum: {sum}"); // 30
Skip Odd Numbers
csharp1for (int i = 1; i <= 10; i++)2{3 if (i % 2 != 0)4 {5 continue; // Skip odd numbers6 }7 Console.WriteLine(i);8}9// Output: 2, 4, 6, 8, 10
Process Valid Records
csharp1string[] records = { "Alice,25", "invalid", "Bob,30", "", "Charlie,28" };23foreach (string record in records)4{5 if (string.IsNullOrEmpty(record) || !record.Contains(","))6 {7 continue; // Skip invalid records8 }910 string[] parts = record.Split(',');11 Console.WriteLine($"Name: {parts[0]}, Age: {parts[1]}");12}
break vs continue
csharp1// break: exits the loop entirely2for (int i = 1; i <= 5; i++)3{4 if (i == 3) break;5 Console.Write($"{i} ");6}7// Output: 1 289Console.WriteLine();1011// continue: skips to next iteration12for (int i = 1; i <= 5; i++)13{14 if (i == 3) continue;15 Console.Write($"{i} ");16}17// Output: 1 2 4 5
break in Nested Loops
break only exits the innermost loop:
csharp1for (int i = 1; i <= 3; i++)2{3 for (int j = 1; j <= 3; j++)4 {5 if (j == 2)6 {7 break; // Only exits inner loop8 }9 Console.Write($"({i},{j}) ");10 }11 Console.WriteLine();12}
Output
1(1,1)2(2,1)3(3,1)
Exiting Multiple Loops
Use a flag or goto (rarely needed):
csharp1// Using a flag2bool found = false;34for (int i = 0; i < 10 && !found; i++)5{6 for (int j = 0; j < 10 && !found; j++)7 {8 if (i * j == 42)9 {10 Console.WriteLine($"Found: {i} * {j} = 42");11 found = true;12 }13 }14}
Practical Examples
Menu Loop with Exit
csharp1while (true)2{3 Console.WriteLine("\n1. Option A");4 Console.WriteLine("2. Option B");5 Console.WriteLine("3. Exit");6 Console.Write("Choose: ");78 string choice = Console.ReadLine() ?? "";910 switch (choice)11 {12 case "1":13 Console.WriteLine("Option A selected");14 break; // Exits switch, not while loop15 case "2":16 Console.WriteLine("Option B selected");17 break;18 case "3":19 Console.WriteLine("Exiting...");20 goto ExitLoop; // Or use a flag21 default:22 continue; // Invalid input, show menu again23 }24}25ExitLoop:26Console.WriteLine("Goodbye!");
Skip Comments in Data
csharp1string[] lines = {2 "# This is a comment",3 "Alice,100",4 "# Another comment",5 "Bob,200",6 "Charlie,300"7};89int total = 0;1011foreach (string line in lines)12{13 if (line.StartsWith("#") || string.IsNullOrWhiteSpace(line))14 {15 continue; // Skip comments and empty lines16 }1718 string[] parts = line.Split(',');19 if (int.TryParse(parts[1], out int value))20 {21 total += value;22 }23}2425Console.WriteLine($"Total: {total}"); // 600
Find Prime Numbers
csharp1Console.WriteLine("Prime numbers from 2 to 50:");23for (int num = 2; num <= 50; num++)4{5 bool isPrime = true;67 for (int i = 2; i < num; i++)8 {9 if (num % i == 0)10 {11 isPrime = false;12 break; // Not prime, stop checking13 }14 }1516 if (!isPrime)17 {18 continue; // Skip non-primes19 }2021 Console.Write($"{num} ");22}23// Output: 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47
Summary
In this lesson, you learned:
breakimmediately exits the current loopcontinueskips the rest of the current iteration- Both only affect the innermost loop in nested loops
- Use break for early termination (found item, quit command)
- Use continue to skip unwanted items (invalid data, filtered items)
Now let's practice with hands-on workshops!