Menu
CoddyTech

foreach、break、continue

Coddyの「C++開発者のためのC#」コースのレッスン 15/48。

C++のrange-forはC#のforeachに対応します。C#の反復処理ではC++のイテレーターを公開するのではなく、列挙子を使用し、コレクションを変更すると列挙が無効になることがあります。whileでは、C++の文脈上の数値変換ではなくbool条件が必要です。

foreachは、インデックスを手動で管理せずに値を順に処理します。breakはループを終了し、continueは次の反復処理に進みます。コレクションではなく、変化する条件によって繰り返しが決まる場合は、whileが便利です。foreachの列挙子が有効な間は、Listを変更しないようにしましょう。

C++の参照コード

#include <algorithm>
#include <array>
#include <cctype>
#include <functional>
#include <iomanip>
#include <iostream>
#include <map>
#include <memory>
#include <optional>
#include <set>
#include <sstream>
#include <stdexcept>
#include <string>
#include <vector>
using namespace std;

int main() {
int value=0;
while(value<3) value++;
cout << value << "\n";
}

Main内のC#ステートメント

int value = 0;
while (value < 3) value++;
Console.WriteLine(value);

これらは、特定の内容に焦点を当てた教材用の抜粋です。課題ファイルには実行可能な完全なラッパーが含まれています。上記のスニペットでは、関連する宣言とステートメントを示しています。

参照出力:

3

C#の出力:

3
challenge icon

チャレンジ

簡単

最初の負の値が現れる前までの配列の正の値を合計します。0はスキップし、最初の負の値より後の値はすべて無視します。入力はカンマ区切りの1行です。

ロックされていないC#ファイルを編集してください。表示されているロック済みのMain.csは、説明されている行を読み取り、Exercise.Solveを呼び出し、入力が変更されていないことを検証して、最後に改行を1つ付けて結果を出力します。宣言済みのAPIを維持してください。2つ目のMainを追加したり、診断出力を表示したりしないでください。

自分で試してみよう

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 icon腕試し

このレッスンには短いクイズがあります。レッスンを始めて解答し、進捗を記録しましょう。

C++開発者のためのC#のすべてのレッスン

自分で練習してみよう: C#オンラインコンパイラ