Menu
CoddyTech

foreach, break e continue

Lição 15 de 48 do curso C# para desenvolvedores de Rust da Coddy.

Um loop for do Rust sobre um iterador corresponde ao foreach do C#, e break e continue se comportam da mesma forma em ambos. A diferença está no momento em que um erro é detectado: o Rust rejeita a tentativa de adicionar um elemento a um Vec dentro do próprio loop for durante a compilação, enquanto o C# compila a mesma alteração para uma List e lança uma InvalidOperationException quando o enumerador a detecta. O C# também não tem break com rótulo nem uma expressão de loop que produza um valor.

foreach percorre os valores sem manter um índice manualmente. break encerra o loop, e continue pula para a próxima iteração. while é útil quando a repetição depende de uma condição que muda, em vez de uma coleção. Evite alterar uma List enquanto seu enumerador foreach estiver ativo.

Referência em Rust

fn main() {
    let mut total = 0;
    for n in [2, -1, 3, 0, 9] {
        if n == 0 {
            break;
        }
        if n < 0 {
            continue;
        }
        total += n;
    }
    println!("{}", total);
}

Instruções em C# dentro de Main

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

Estes são trechos didáticos focados. Os arquivos do desafio incluem wrappers executáveis completos; os trechos acima mostram as declarações e instruções relevantes.

Saída do Rust:

5

Saída do C#:

5
challenge icon

Desafio

Fácil

Some 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.

Experimente você mesmo

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 iconTeste seus conhecimentos

Esta lição inclui um quiz rápido. Comece a lição para respondê-lo e acompanhar seu progresso.

Todas as lições de C# para desenvolvedores de Rust

Pratique por conta própria: Compilador de C# online