Menu
CoddyTech

foreach, break and continue

Lesson 15 of 48 in Coddy's C# for C Developers course.

C has no foreach: you walk an index from 0 to a count you work out yourself, often with sizeof values / sizeof values[0], which only works on a real array and silently breaks on a pointer. C# foreach asks the collection for its elements, and an array carries its own Length, so there is no count to get wrong and no index to run past the end. break and continue mean what they mean in C. A C# loop condition must be a bool: while (n) does not compile, so write while (n != 0).

Foreach visits values without manually maintaining an index. Break ends the loop and continue skips to its next iteration. While is useful when repetition depends on a changing condition instead of a collection. Avoid changing a List while its foreach enumerator is active.

C reference

#include <stdio.h>

int main(void) {
    int values[] = {2, -1, 3, 0, 9};
    size_t count = sizeof values / sizeof values[0];
    int total = 0;
    for (size_t i = 0; i < count; i++) {
        if (values[i] == 0) break;
        if (values[i] < 0) continue;
        total += values[i];
    }
    printf("%d\n", total);
    return 0;
}

C# statements inside Main

int[] values = { 2, -1, 3, 0, 9 };
int total = 0;
foreach (int n in values)
{
    if (n == 0) break;
    if (n < 0) continue;
    total += n;
}
Console.WriteLine(total);

These are focused teaching excerpts. The challenge files include complete executable wrappers; the snippets above show the relevant declarations and statements.

Reference output:

5

C# output:

5
challenge icon

Challenge

Easy

Sum positive array values before the first negative value; skip zeros and ignore everything after the first negative. Input is one comma-separated line.

Edit the unlocked C# files. The visible locked Main.cs reads the described lines, calls Exercise.Solve, verifies input was not mutated and prints the result with one final newline. Keep the declared APIs. Do not add a second Main or print diagnostic output.

Try it yourself

using System;
using System.Linq;
using System.Collections.Generic;
using System.Globalization;
public class Program {
static int I(string text) { return int.Parse(text,CultureInfo.InvariantCulture); }
static int[] Ints(string text) { return text.Length==0 ? new int[0] : text.Split(',').Select(I).ToArray(); }
static string[] Words(string text) { return text.Length==0 ? new string[0] : text.Split(','); }
static string Snapshot(object value) { if (value==null) return "<null>"; if (value is string) return (string)value; var sequence=value as System.Collections.IEnumerable; if (sequence!=null) { var items=new List<string>(); foreach (object item in sequence) items.Add(Snapshot(item)); return string.Join("|",items); } return Convert.ToString(value,CultureInfo.InvariantCulture); }
public static void Main() {
System.Threading.Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
var rows = new List<string>(); string line; while ((line=Console.ReadLine()) != null) rows.Add(line);
string[] input=rows.ToArray();
var a0 = Ints(input[0]); string before0=Snapshot(a0);

var result = Exercise.Solve(a0);
if (Snapshot(a0) != before0) throw new Exception("Input mutation");
Console.WriteLine(result);
}
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in C# for C Developers

Practice on your own: Online C# compiler