8 minlesson

Break and Continue Statements

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:

csharp
1for (int i = 1; i <= 10; i++)
2{
3 if (i == 5)
4 {
5 break; // Exit the loop
6 }
7 Console.WriteLine(i);
8}
9Console.WriteLine("Done");

Output

11
22
33
44
5Done

The loop stops when i equals 5, and 5 is never printed.

break Use Cases

Search and Stop

csharp
1int[] numbers = { 4, 8, 15, 16, 23, 42 };
2int searchFor = 16;
3int foundIndex = -1;
4
5for (int i = 0; i < numbers.Length; i++)
6{
7 if (numbers[i] == searchFor)
8 {
9 foundIndex = i;
10 break; // Found it, no need to continue
11 }
12}
13
14if (foundIndex >= 0)
15{
16 Console.WriteLine($"Found at index {foundIndex}");
17}

User Quits

csharp
1while (true)
2{
3 Console.Write("Enter command (q to quit): ");
4 string input = Console.ReadLine() ?? "";
5
6 if (input.ToLower() == "q")
7 {
8 break; // Exit the infinite loop
9 }
10
11 Console.WriteLine($"Processing: {input}");
12}
13Console.WriteLine("Goodbye!");

First Match

csharp
1string[] names = { "Alice", "Bob", "Charlie", "Diana" };
2string firstWithA = "";
3
4foreach (string name in names)
5{
6 if (name.StartsWith("A"))
7 {
8 firstWithA = name;
9 break;
10 }
11}
12
13Console.WriteLine($"First name starting with A: {firstWithA}");

The continue Statement

continue skips the rest of the current iteration and moves to the next:

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

Output

11
22
34
45

The number 3 is skipped.

continue Use Cases

Skip Invalid Items

csharp
1string[] inputs = { "5", "abc", "10", "", "15" };
2int sum = 0;
3
4foreach (string input in inputs)
5{
6 if (!int.TryParse(input, out int number))
7 {
8 continue; // Skip non-numeric inputs
9 }
10 sum += number;
11}
12
13Console.WriteLine($"Sum: {sum}"); // 30

Skip Odd Numbers

csharp
1for (int i = 1; i <= 10; i++)
2{
3 if (i % 2 != 0)
4 {
5 continue; // Skip odd numbers
6 }
7 Console.WriteLine(i);
8}
9// Output: 2, 4, 6, 8, 10

Process Valid Records

csharp
1string[] records = { "Alice,25", "invalid", "Bob,30", "", "Charlie,28" };
2
3foreach (string record in records)
4{
5 if (string.IsNullOrEmpty(record) || !record.Contains(","))
6 {
7 continue; // Skip invalid records
8 }
9
10 string[] parts = record.Split(',');
11 Console.WriteLine($"Name: {parts[0]}, Age: {parts[1]}");
12}

break vs continue

csharp
1// break: exits the loop entirely
2for (int i = 1; i <= 5; i++)
3{
4 if (i == 3) break;
5 Console.Write($"{i} ");
6}
7// Output: 1 2
8
9Console.WriteLine();
10
11// continue: skips to next iteration
12for (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:

csharp
1for (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 loop
8 }
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):

csharp
1// Using a flag
2bool found = false;
3
4for (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

csharp
1while (true)
2{
3 Console.WriteLine("\n1. Option A");
4 Console.WriteLine("2. Option B");
5 Console.WriteLine("3. Exit");
6 Console.Write("Choose: ");
7
8 string choice = Console.ReadLine() ?? "";
9
10 switch (choice)
11 {
12 case "1":
13 Console.WriteLine("Option A selected");
14 break; // Exits switch, not while loop
15 case "2":
16 Console.WriteLine("Option B selected");
17 break;
18 case "3":
19 Console.WriteLine("Exiting...");
20 goto ExitLoop; // Or use a flag
21 default:
22 continue; // Invalid input, show menu again
23 }
24}
25ExitLoop:
26Console.WriteLine("Goodbye!");

Skip Comments in Data

csharp
1string[] lines = {
2 "# This is a comment",
3 "Alice,100",
4 "# Another comment",
5 "Bob,200",
6 "Charlie,300"
7};
8
9int total = 0;
10
11foreach (string line in lines)
12{
13 if (line.StartsWith("#") || string.IsNullOrWhiteSpace(line))
14 {
15 continue; // Skip comments and empty lines
16 }
17
18 string[] parts = line.Split(',');
19 if (int.TryParse(parts[1], out int value))
20 {
21 total += value;
22 }
23}
24
25Console.WriteLine($"Total: {total}"); // 600

Find Prime Numbers

csharp
1Console.WriteLine("Prime numbers from 2 to 50:");
2
3for (int num = 2; num <= 50; num++)
4{
5 bool isPrime = true;
6
7 for (int i = 2; i < num; i++)
8 {
9 if (num % i == 0)
10 {
11 isPrime = false;
12 break; // Not prime, stop checking
13 }
14 }
15
16 if (!isPrime)
17 {
18 continue; // Skip non-primes
19 }
20
21 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:

  • break immediately exits the current loop
  • continue skips 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!

Break and Continue Statements - Anko Academy