Menu
Coddy logo textTech

איטרציה במבנים מורכבים

חלק מהיחידה לוגיקה וזרימת תוכנית במסלול ה-C# של Coddy. שיעור 14 מתוך 66.

מעבר על מבנים מורכבים כמו מערכים מקוננים דורש גישות מיוחדות.

עוברים על מערך דו־ממדי באמצעות לולאות מקוננות:

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}");
challenge icon

אתגר

קל

צרו מתודה בשם countElements ש:

  1. מקבלת מערך משונן של מחרוזות (string[][]) כפרמטר
  2. סופרת כמה איברים יש במערך המשונן כולו
  3. מחזירה את הספירה הכוללת

לדוגמה, בהינתן:

[
  ["apple", "orange", "apple"],
  ["banana", "apple"],
  ["orange"]
]

התוצאה צריכה להיות 6 (3 + 2 + 1).

נסו בעצמכם

using System;
public class CountElements
{
    // ממשו את המתודה countElements
    public static int countElements(string[][] nestedArray)
    {
        // כתבו את הקוד שלכם כאן
        
    }
}
quiz iconבחנו את עצמכם

השיעור הזה כולל חידון קצר. התחילו את השיעור כדי לענות עליו ולעקוב אחרי ההתקדמות.

כל השיעורים ביחידה לוגיקה וזרימת תוכנית

תרגלו בעצמכם: קומפיילר C# אונליין