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

one + twenty =

Share this Doc

Iterating Through Arrays

Or copy link