C# Break and Continue: Stop a Search or Skip an Item
Stop when the answer is complete; skip when only the current item is unsuitable. Learn where break, continue and return send execution, keep every loop path progressing, and make search summaries accurate.
What you will understand
- Choose break or continue from the stated data-processing rule.
- Trace continue through for, foreach, while and do-while control flow.
- Preserve loop progress on every skipping path.
- Retain the first matching position and distinguish it from no match.
- Identify the nearest loop or switch affected by break.
- Distinguish a loop exit from a method return.
- Count inspected and accepted items deliberately.
- Test skipped records, duplicate matches, empty inputs and no-match outcomes.
Choose stop or skip from the meaning of the data
break ends a scan; continue skips the remaining work for one item. Both are ordinary control-flow statements whose usefulness depends on the question. An invalid record might need to be skipped, reported, or treated as a fatal problem. Decide that policy before choosing the keyword.
In the sentinel example, zero means no further values should be processed, so break is appropriate. In the quantity example, a nonpositive value is unusable but later values remain worth inspecting, so continue is appropriate. The same numeric value can play different roles under different documented rules.
You need the previous loop, Boolean and string lessons. Every editor contains a complete Program.cs. All reference programs are finite, including the deliberately broken examples. Trace where control goes next rather than relying on the output labels to explain the jump.
Program.cs · Stop before processing the sentinel
Predict the result, edit Program.cs, then run your program.
Standard input · optional
Select Run code to compile and execute this program.
Processed: 2
Processed: 4
After loop.
Zero is a documented stopping marker in this example, not invalid data to skip. break exits the foreach before zero or later values are printed. Execution still reaches the statement after the loop. The condition around break determines when the jump happens.
Program.cs · Skip one unsuitable item and keep looking
Predict the result, edit Program.cs, then run your program.
Standard input · optional
Select Run code to compile and execute this program.
Usable quantity: 2
Usable quantity: 3
Scan finished.
continue skips the rest of the current body. foreach then advances to the next element. Here nonpositive quantities are unusable entries, so stopping the whole scan would lose the later valid value. Choose skip or stop from the data rule, not merely from whether a condition looks exceptional.
Continue still needs a path that advances the loop
In for, continue proceeds to the iterator section before the next condition check. In foreach, it advances enumeration to the next item. It does not repeat the same element automatically and it does not stop the traversal.
A while loop has no built-in iterator section. If its index update appears below a continue, that path skips the update and can become stuck. Capture the current element and advance the index before a possible continue, or structure the body so every continuing path updates appropriately.
Do-while checks its trailing condition after continue, rather than returning straight to the first body statement without a check. The common principle is to identify the loop’s actual next step. A condition must eventually become false or an exit must be reached; the jump itself is not proof of progress.
Program.cs · A for iterator still runs after continue
Predict the result, edit Program.cs, then run your program.
Standard input · optional
Select Run code to compile and execute this program.
Number: 1
Number: 3
Number: 4
continue in this for loop goes through the iterator number++ before the next condition check. It skips the output for two, not the header update. This behavior differs from a while loop whose update is an ordinary statement at the bottom of the body.
Program.cs · Advance a while index before a skipping path
Predict the result, edit Program.cs, then run your program.
Standard input · optional
Select Run code to compile and execute this program.
Value: 2
Value: 3
Positions visited: 4
The source value is captured, then index advances before continue can skip later work. Moving index++ only to the bottom would leave the index stuck on the first zero. Trace every continuing path to verify it either advances or exits; do not run an unbounded broken variant just to observe a timeout.
Record the result before ending a first-match search
A first-match search needs a clear no-match state and a place to retain the result after the loop. With zero-based indexes, -1 is a useful sentinel because zero is a valid position. Check foundIndex < 0 before claiming a match.
Once a matching item is found, store its position before break. Continuing to scan can overwrite that first result with a later duplicate. If the requirement is all matches, a single result and early break are the wrong design: use a different result collection or count.
A search summary also needs precise language. Found position refers to the original source index, not the count of accepted records or a one-based display label. Skipping blank entries does not renumber the underlying array.
Program.cs · Keep the first matching position
Predict the result, edit Program.cs, then run your program.
Standard input · optional
Select Run code to compile and execute this program.
First position: 1
The -1 value means no position has matched. Index zero would be a real first-element match, so it cannot serve as the not-found marker. Assign the matching position before breaking; otherwise the summary would lose it. The second equal code is not inspected after the first match ends the search.
Find the nearest construct affected by the jump
An unlabelled break exits the nearest enclosing loop or switch. In nested loops, it exits the inner loop only. The outer iteration continues after that inner statement unless its own logic also exits. This lesson stays within the C# 14 syntax used by the runner.
A switch inside a loop is a common source of confusion. break in a case normally leaves the switch, so statements after the switch still run in the same loop iteration. continue targets a loop, not a switch; when placed in a switch inside a loop, it skips the remaining body of that loop iteration.
return has a wider purpose: it leaves the current method. In these top-level programs, it ends the run. Do not replace a loop break with return if a required post-loop summary should still run. Choose the narrowest exit that matches the actual requirement.
Program.cs · An unlabelled break exits only the nearest loop
Predict the result, edit Program.cs, then run your program.
Standard input · optional
Select Run code to compile and execute this program.
Group 1, slot 1
Group 1 finished.
Group 2, slot 1
Group 2 finished.
The break belongs to the inner loop. It does not end the outer loop or the program. The outer body continues with its summary, then begins its next iteration. These examples use unlabelled jumps supported by the course’s C# 14 runner; newer language features are not required.
Program.cs · A switch break does not stop its surrounding loop
Predict the result, edit Program.cs, then run your program.
Standard input · optional
Select Run code to compile and execute this program.
Inside skip case.
After switch in the same iteration.
Inside read case.
After switch in the same iteration.
The nearest breakable statement here is switch, so each break exits that statement only. The following output in the loop still runs. A continue inside a switch nested in a loop would instead target the loop’s next iteration; use that only when the whole remaining loop body should be skipped.
Program.cs · Return bypasses the post-loop summary too
Predict the result, edit Program.cs, then run your program.
Standard input · optional
Select Run code to compile and execute this program.
Value: 2
Ending this run.
return ends this top-level program, so Scan summary is never reached for the reference input. break would preserve the post-loop summary. Neither is inherently better: the correct jump depends on whether you want to stop a scan or leave the entire current method.
Counters before and after a skip tell different stories
A visited count includes every record inspected. An accepted count includes only records that satisfy the rule. They are different measurements. Increment visited before a skipping guard, and increment accepted or a total only after the item has passed the guard.
An early break also limits the visited count. A first match at index three means four records were inspected in a zero-based sequential scan, even if some were rejected. It does not mean the full collection was validated.
Do not put required bookkeeping after a path that skips it. Read the summary requirement first, then place each update accordingly. The quantities example makes its three results explicit instead of using an ambiguous count variable for all of them.
Program.cs · Count visited and accepted items separately
Predict the result, edit Program.cs, then run your program.
Standard input · optional
Select Run code to compile and execute this program.
Visited: 4
Accepted: 2
Total: 5
visited increases before the guard and counts every inspected value. accepted and total change only after an item passes the rule. Counter placement defines the meaning of the summary. Moving all counters below continue would erase evidence that rejected items were visited.
A guard should simplify the remaining work
A short continue guard can remove a layer of nesting: skip missing or blank text, then let the rest of the iteration work with a usable string. It is especially helpful when the remaining work would otherwise sit inside a large else block.
Too many scattered jumps can still obscure the purpose. Keep the order consistent: account for the visited record, reject or skip unsuitable data, perform the intended work, and stop when the result is complete. Avoid hidden mutations in conditions.
Preserve the distinction between cleanup and validation. Trimming a code and using OrdinalIgnoreCase defines a matching policy for this exercise. It does not validate every identifier format or establish the existence of an actual course.
Test what happens before, at and after the stopping point
Test a match at the first element, a match after rejected items, multiple matches and no match. An empty array should reach a clear no-match result with zero inspections. A duplicate after the first match should not affect a first-match answer.
Test skipped values at the beginning, middle and end. They should not accidentally end the scan. For while loops, inspect the update on each skipping path so repeated rejected values cannot trap the loop at one index.
Finally, verify the scope of the exit: does the post-loop summary still run, does the outer loop continue, and does a switch break leave the intended construct? These are observable parts of the program’s behavior, not just style preferences.
Guided repair: a blank record must not end the search
A blank record at the beginning prevents the program from finding a later course code. Change only the jump that represents an unusable item, preserving the first-match stop and its stored result.
Program.cs · Stopping at unusable text loses later matches
Predict the result, edit Program.cs, then run your program.
Standard input · optional
Select Run code to compile and execute this program.
Found position: -1
A blank code is an unusable record under this rule, not an instruction to stop. The first break ends the scan before any useful code is checked. The matching break has a different purpose: it should remain because the task asks for the first match.
Repair checkpoints
- Blank or missing records must skip to the next source position.
- The match path must store foundIndex before stopping.
- The reference first match is index 2.
- Move the target to the first position: zero must be reported as a valid match.
- With no matching code, retain -1 rather than inventing a match.
Reveal the repair and explanation
Program.cs · Skip unusable records and stop only on a match
Predict the result, edit Program.cs, then run your program.
Standard input · optional
Select Run code to compile and execute this program.
Found position: 2
continue advances the for loop after an unusable record. break ends it after a successful match. The search preserves original array positions, including skipped entries. Trimming and case-insensitive ordinal comparison are the stated code-token policy, not full identifier validation.
Independent lab: find the first usable course-code match
Search for the first course code matching a fixed target after trimming and case-insensitive ordinal comparison. Skip missing and blank records, count every inspected record, and stop immediately after the first match.
Acceptance checklist
- Use the five fixed entries and target from the starter.
- Count a record before any skipping guard.
- Use continue for null, empty and whitespace-only entries.
- Compare the trimmed present code with the target using OrdinalIgnoreCase.
- Store its original zero-based position and break after the first match.
- Print Inspected: 4 and Found position: 3 for the reference source.
- Report No matching course code when no match exists; do not claim to query a real catalog.
Program.cs · Course-code search starter
Predict the result, edit Program.cs, then run your program.
Standard input · optional
Select Run code to compile and execute this program.
Inspected: 0
Found position: -1
The starter stops at a missing record, excludes rejected items from its inspected count, uses an unsuitable exact comparison and would keep scanning after a match. The lab defines each of those policies explicitly so the repair is more than changing one keyword.
Show hints
- Initialize foundIndex to -1 outside the loop.
- The visited count belongs before the blank-record check.
- Keep break only on the successful match path, after recording the index.
Reveal the reference solution
Program.cs · Course-code search reference solution
Predict the result, edit Program.cs, then run your program.
Standard input · optional
Select Run code to compile and execute this program.
Inspected: 4
Found position: 3
The count includes every visited record, including missing and blank entries. The first normalized match is at index three, so only four records are inspected and the duplicate at index four is not visited. This is a local search over supplied values; a matching token does not prove that a course exists in a published catalog.
Changed-input checks
- A first-element match reports index 0 and one inspection.
- An empty array reports zero inspections and no match.
- All blank or missing entries are counted but produce no match.
- A target after blank entries is still found.
- For duplicate matches, the first source position wins and later entries are not inspected.
- Changing the target to an absent code inspects the full array and reports no match.
Recap: choose the intended scope of the jump
Choose stop, skip or leave the method from the requirement. Preserve progress, record results before exiting, and place counters according to what they measure.
break- Exit the nearest enclosing loop or switch and continue afterward.
continue- Skip the rest of the current loop body and follow its next-iteration path.
return- Leave the current method or this top-level run.
for iterator- Still runs after continue before the next condition check.
while update- An ordinary body statement; a continue can skip it if placed too late.
foundIndex = -1- Represent no match without confusing it with valid position zero.
inspected++ before guard- Count every visited record, including those skipped.
assign result, then break- Retain the first match without processing later duplicates.
Frequently asked questions
Does continue stop the loop?
No. It skips the remaining body for this iteration, then follows the loop’s next-iteration path.
Does a for increment still happen after continue?
Yes, the iterator section runs before the next condition check. A while loop update is an ordinary statement that can be skipped, so its placement needs care.
Does break exit every nested loop?
An unlabelled break exits only the nearest enclosing loop or switch. Additional outer control flow is needed if the whole search spans several loops.
Why use -1 for a missing index?
Zero is a valid first position. A distinct sentinel lets the summary distinguish no match from a match at the first item.
Why count inspected before continue?
That count describes every visited record, including rejected ones. A count of usable records belongs after the guard and should be named differently.
Can I use return instead of break?
Only when leaving the current method is the intended behavior. In these top-level examples return ends the run and skips any remaining summary.
Can you trace where control goes next?
Identify the target of each jump and verify progress and summaries. Read the explanation after checking your answers.
Next step and references
Loop control should make the purpose clearer: skip an unsuitable item, stop a completed search or leave the current method. Verify every continuing path advances, and every summary describes the records actually inspected.
Next is C# Arrays and Multidimensional Data. You will create and traverse fixed-size arrays, check bounds, and compare rectangular and jagged shapes.
Official references
Original SovranCode explanations, examples and exercises. Technical details were checked against these references.
Last updated: .