C# Foundations · Lesson 31

Continue, break, and a processing sentinel

Distinguish skipping one item from ending a whole loop.

How it works

Continue moves control to the next iteration of the nearest enclosing loop. Break ends that loop entirely. These statements answer different questions: should this particular item be ignored, or should no more items be processed? Making that distinction explicit keeps an input-processing loop aligned with its data protocol.

A sentinel is a special value that marks the end of useful input. It is part of the input contract and should not also be a legitimate data value. In this example zero ends a batch, while negative values are invalid records that are skipped. The order of the tests expresses those policies before the accepted-value calculation begins.

Walk through the example. The loop accepts five, skips negative two, accepts seven, and then encounters zero. Break stops processing at that point, so ninety-nine is never added. A counter is updated only after both guards, meaning it counts accepted records rather than all examined records. The printed result contains an accepted count of two and a total of twelve.

Watch the boundary. Continue and break affect only the nearest loop. In nested processing, a break does not automatically leave every enclosing loop. Also think carefully before using zero as a sentinel in a domain where zero could be an ordinary measurement. An explicit record type or an end-of-sequence boundary can communicate termination without sacrificing a valid value.

Practice independently. Write a processor that skips blank labels, stops at an explicit END label, and counts the remaining labels. Define whether the sentinel comparison is case-sensitive. Test a sentinel at the beginning, a batch with no sentinel, consecutive skipped items, and valid items after the sentinel. Then replace the sentinel with a bounded list and compare how the termination contract changes.

A working example

using System;
using System.Collections.Generic;
using System.Linq;
using System.Globalization;
using System.Text;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Text.RegularExpressions;

int count = 0, total = 0;
foreach (int value in new[] { 5, -2, 7, 0, 99 })
{
    if (value == 0) break;
    if (value < 0) continue;
    count++;
    total += value;
}
Console.WriteLine($"accepted:{count}");
Console.WriteLine($"total:{total}");

Expected output

accepted:2
total:12
Try this
Use continue for one rejected record and break for an explicit end-of-batch rule.