複雑な反復処理
CoddyのC#ジャーニー「ロジックとフロー」セクションの一部。レッスン 14/66。
ネストされた配列のような複雑な構造を反復処理するには、特別な方法が必要です。
ネストしたループを使って2次元配列を反復処理します:
int[][] matrix = new int[3][];
matrix[0] = new int[] { 1, 2, 3 };
matrix[1] = new int[] { 4, 5, 6 };
matrix[2] = new int[] { 7, 8, 9 };
for (int i = 0; i < matrix.Length; i++)
{
for (int j = 0; j < matrix[i].Length; j++)
{
Console.WriteLine(matrix[i][j]);
}
}文字列配列を反復処理し、各文字を処理します:
string[] words = { "hello", "world" };
for (int i = 0; i < words.Length; i++)
{
for (int j = 0; j < words[i].Length; j++)
{
Console.WriteLine(words[i][j]);
}
}ジャグ配列内の項目を数える:
int[][] jaggedArray = new int[3][];
jaggedArray[0] = new int[] { 1, 2, 3 };
jaggedArray[1] = new int[] { 4, 5 };
jaggedArray[2] = new int[] { 6 };
int totalItems = 0;
for (int i = 0; i < jaggedArray.Length; i++)
{
totalItems += jaggedArray[i].Length;
}
Console.WriteLine($"Total items: {totalItems}");チャレンジ
簡単countElementsというメソッドを作成してください。このメソッドは次の処理を行います:
- 文字列のジャグ配列(string[][])をパラメーターとして受け取る
- ジャグ配列全体に含まれる要素数を数える
- 合計数を返す
たとえば、次の配列の場合:
[
["apple", "orange", "apple"],
["banana", "apple"],
["orange"]
]結果は6(3 + 2 + 1)になります。
自分で試してみよう
using System;
public class CountElements
{
// countElements メソッドを実装してください
public static int countElements(string[][] nestedArray)
{
// ここにコードを書いてください
}
}このレッスンには短いクイズがあります。レッスンを始めて解答し、進捗を記録しましょう。
ロジックとフローのすべてのレッスン
自分で練習してみよう: C#オンラインコンパイラ