Complete C# Tutorial

Iterating Through Arrays in C#: Simple Guide with Examples

๐Ÿ‘‹ Introduction

Hey there! ๐Ÿ˜ƒ Have you ever wondered how to go through each item in an array without manually accessing them one by one? Imagine checking every book on a shelfโ€”picking them one at a time would be tiring, right? Well, thatโ€™s where Iterating Through Arrays in C# saves the day! Itโ€™s like having a robot pick each book for you. ๐Ÿ“š

In this lesson, youโ€™ll explore different ways to iterate through arrays in a super fun and friendly way. So, grab your coding gear and letโ€™s dive in! ๐Ÿš€

1๏ธโƒฃ Iterating Through Single Dimensional Arrays

๐Ÿ› ๏ธ 1. Using the for Loop: The Classic Way

๐Ÿ“ Syntax:

				
					for (int i = 0; i < array.Length; i++) {
    // Access array elements using array[i]
}
				
			

๐Ÿ’ป Example:

Letโ€™s say you have a list of your favorite snacks. ๐Ÿฅจ๐Ÿ•๐Ÿซ

				
					using System;

class Program {
    static void Main() {
        string[] snacks = { "Chips", "Pizza", "Chocolate" };

        Console.WriteLine("My favorite snacks:");
        for (int i = 0; i < snacks.Length; i++) {
            Console.WriteLine($"Snack {i + 1}: {snacks[i]}");
        }
    }
}
				
			

๐Ÿ–ฅ๏ธ Output:

				
					My favorite snacks:
Snack 1: Chips
Snack 2: Pizza
Snack 3: Chocolate
				
			

๐Ÿค” Explanation:

  • for (int i = 0; i < snacks.Length; i++): Starts from index 0 and runs until the end of the array.
  • snacks[i]: Accesses each snack in the array.
  • Easy, right? Itโ€™s like checking every item in your shopping list! ๐Ÿ›’

๐Ÿ”„ 2. Using the foreach Loop: Simpler and Cleaner

๐Ÿ“ Syntax:

				
					foreach (var item in array) {
    // item represents the current element
}
				
			

๐Ÿ’ป Example:

Imagine reading names from your class attendance list. ๐Ÿ“

				
					using System;

class Program {
    static void Main() {
        string[] students = { "Steven", "Emma", "Olivia" };

        Console.WriteLine("Class Attendance:");
        foreach (string student in students) {
            Console.WriteLine(student);
        }
    }
}
				
			

๐Ÿ–ฅ๏ธ Output:

				
					Class Attendance:
Steven
Emma
Olivia
				
			

๐Ÿค“ Why use foreach?

  • No need to worry about indexes.
  • Perfect for when you just need the item, not the index.
  • Super clean and beginner-friendly! ๐ŸŒŸ

โณ 3. Using the while Loop: When You Need More Control

๐Ÿ“ Syntax:

				
					int i = 0;
while (i < array.Length) {
    // Do something with array[i]
    i++;
}
				
			

๐Ÿ’ป Example:

Letโ€™s count the coins in a piggy bank! ๐Ÿท๐Ÿ’ฐ

				
					using System;

class Program {
    static void Main() {
        int[] coins = { 1, 5, 10, 25 };
        int i = 0;

        Console.WriteLine("Counting coins:");
        while (i < coins.Length) {
            Console.WriteLine($"Coin: {coins[i]} cents");
            i++;
        }
    }
}
				
			

๐Ÿ–ฅ๏ธ Output:

				
					Counting coins:
Coin: 1 cents
Coin: 5 cents
Coin: 10 cents
Coin: 25 cents
				
			

๐Ÿค” Why use while?

  • Great when the loop depends on conditions other than just reaching the end.
  • More flexibility, but remember to increment i or youโ€™ll loop forever! ๐Ÿ˜ฑ

๐Ÿ” 4. Using the do-while Loop: Do First, Check Later!

๐Ÿ“ Syntax:

				
					int i = 0;
do {
    // Do something with array[i]
    i++;
} while (i < array.Length);
				
			

๐Ÿ’ป Example:

Imagine playing a song playlist that plays at least once. ๐ŸŽต

				
					using System;

class Program {
    static void Main() {
        string[] songs = { "Song A", "Song B", "Song C" };
        int i = 0;

        Console.WriteLine("Playing songs:");
        do {
            Console.WriteLine(songs[i]);
            i++;
        } while (i < songs.Length);
    }
}
				
			

๐Ÿ–ฅ๏ธ Output:

				
					Playing songs:
Song A
Song B
Song C
				
			

๐Ÿค” Why use do-while?

  • Guarantees the code runs at least once.
  • Useful when you want an action before checking conditions.

๐ŸŒ Real-World Scenario: Checking Student Grades

Imagine youโ€™re a teacher checking studentsโ€™ scores. You want to know who passed. ๐ŸŽ“

				
					using System;

class Program {
    static void Main() {
        int[] scores = { 85, 60, 90, 40, 70 };
        int passMark = 60;

        Console.WriteLine("Pass/Fail Report:");
        for (int i = 0; i < scores.Length; i++) {
            if (scores[i] >= passMark) {
                Console.WriteLine($"Student {i + 1}: Passed โœ…");
            } else {
                Console.WriteLine($"Student {i + 1}: Failed โŒ");
            }
        }
    }
}
				
			

๐Ÿ–ฅ๏ธ Output:

				
					Pass/Fail Report:
Student 1: Passed โœ…
Student 2: Passed โœ…
Student 3: Passed โœ…
Student 4: Failed โŒ
Student 5: Passed โœ…
				
			

๐Ÿ˜Ž Explanation:

  • Iterates through the scores array.
  • Checks if each score meets the pass mark.
  • Perfect for reports or evaluations. ๐Ÿ“Š

2๏ธโƒฃ Iterating Through Multidimensional Arrays: Rows and Columns!

Alright, letโ€™s level up! ๐ŸŒŸ A multidimensional array is like a gridโ€”a table with rows and columns.

๐Ÿ“ Syntax:

				
					for (int i = 0; i < rows; i++) {
    for (int j = 0; j < columns; j++) {
        // Access element with array[i, j]
    }
}
				
			

๐Ÿ’ป Example 1: Seating Arrangement

Imagine youโ€™re checking seat numbers in a classroom. ๐Ÿช‘

				
					using System;

class Program {
    static void Main() {
        int[,] seats = {
            {101, 102, 103},
            {201, 202, 203},
            {301, 302, 303}
        };

        Console.WriteLine("Seating Arrangement:");
        for (int i = 0; i < seats.GetLength(0); i++) {
            for (int j = 0; j < seats.GetLength(1); j++) {
                Console.Write($"{seats[i, j]} ");
            }
            Console.WriteLine(); // Move to next row
        }
    }
}
				
			

๐Ÿ–ฅ๏ธ Output:

				
					Seating Arrangement:
101 102 103 
201 202 203 
301 302 303 
				
			

๐Ÿง Explanation:

  • seats.GetLength(0): Number of rows.
  • seats.GetLength(1): Number of columns.
  • Loops through each row and column to print seat numbers.
  • Feels like checking seating in a theater! ๐ŸŽญ

๐Ÿ’ป Example 2: Student Grades Table

Letโ€™s create a grades table. Imagine checking test scores for students. ๐Ÿ“Š

				
					using System;

class Program {
    static void Main() {
        int[,] grades = {
            {85, 90, 78}, // Student 1 scores
            {88, 76, 92}, // Student 2 scores
            {91, 89, 95}  // Student 3 scores
        };

        Console.WriteLine("Student Grades:");
        for (int i = 0; i < grades.GetLength(0); i++) {
            Console.Write($"Student {i + 1}: ");
            for (int j = 0; j < grades.GetLength(1); j++) {
                Console.Write($"{grades[i, j]} ");
            }
            Console.WriteLine();
        }
    }
}
				
			

๐Ÿ–ฅ๏ธ Output:

				
					Student Grades:
Student 1: 85 90 78 
Student 2: 88 76 92 
Student 3: 91 89 95 
				
			

๐Ÿ˜Ž Why itโ€™s useful:

  • Quickly see how each student performed.
  • Great for handling data like spreadsheets. ๐Ÿ“‘

๐ŸŒ Real-World Scenario: Monthly Sales Report

Imagine managing sales for a store over three months. You want to see how each product performed. ๐Ÿ›๏ธ๐Ÿ’ต

				
					using System;

class Program {
    static void Main() {
        int[,] sales = {
            {100, 120, 130}, // Product A sales
            {80, 90, 100},   // Product B sales
            {150, 160, 170}  // Product C sales
        };

        Console.WriteLine("Monthly Sales Report:");
        for (int i = 0; i < sales.GetLength(0); i++) {
            Console.Write($"Product {Convert.ToChar('A' + i)}: ");
            for (int j = 0; j < sales.GetLength(1); j++) {
                Console.Write($"{sales[i, j]} ");
            }
            Console.WriteLine();
        }
    }
}
				
			

๐Ÿ–ฅ๏ธ Output:

				
					Monthly Sales Report:
Product A: 100 120 130 
Product B: 80 90 100 
Product C: 150 160 170 
				
			

๐Ÿ˜ƒ Explanation:

  • Loops through rows (products) and columns (months).
  • Quick way to analyze trends.
  • Useful for reports and analytics! ๐Ÿ“ˆ

๐ŸŽฏ Conclusion

Wow! Youโ€™ve just mastered Iterating Through Arrays in C#! ๐ŸŽ‰ Isnโ€™t it cool how you can explore every element without the hassle? Whether youโ€™re checking items, counting coins, or reviewing grades, knowing how to iterate arrays is super handy.

I know it might feel like a lot, but donโ€™t worryโ€”youโ€™ve got this! ๐Ÿ˜Ž Keep practicing, play around with examples, and soon itโ€™ll feel like second nature. Coding should be fun, right? ๐Ÿ˜‰

ย 

๐Ÿš€ Next what?

Guess whatโ€™s next? In the upcoming chapter, youโ€™ll learn Passing Array as Parameter in C#. Imagine sending a whole list to a method and saving tons of time! Stay excited, keep coding, and see you there! ๐ŸŽฏ๐Ÿ’ช

Leave a Comment

Share this Doc

Iterating Through Arrays

Or copy link