DEV Community

mohamed Tayel
mohamed Tayel

Posted on

Introduction to Arrays

Arrays are one of the most fundamental collection types in C#. They allow you to store multiple related values in a single, ordered collection. Whether you're managing days of the week, student grades, or product prices, arrays make data organization and manipulation more efficient.

In this article, we’ll cover:

  1. What arrays are.
  2. How to create and initialize them.
  3. Accessing, modifying, and enumerating array elements.
  4. A practical example: Building a Weekly Task Manager.

1. What Is an Array?

An array is:

  • A fixed-size collection: Once created, the size cannot change.
  • Ordered: Each item in an array has a specific position (index).
  • Zero-indexed: The first element is at index 0, the second at 1, and so on.

2. Creating and Initializing Arrays

Example: Storing Days of the Week

string[] daysOfWeek = { "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday" };
Enter fullscreen mode Exit fullscreen mode

Here:

  • string[] specifies that the array stores strings.
  • { ... } contains the array’s initial values.

Accessing Items

Console.WriteLine(daysOfWeek[0]); // Output: Monday
Enter fullscreen mode Exit fullscreen mode

Modifying Items

daysOfWeek[2] = "Weds"; // Updates Wednesday to Weds
Enter fullscreen mode Exit fullscreen mode

3. Enumerating an Array

You can iterate through an array using a foreach loop:

Example

foreach (string day in daysOfWeek)
{
    Console.WriteLine(day);
}
Enter fullscreen mode Exit fullscreen mode

This prints:

Monday
Tuesday
Wednesday
Thursday
Friday
Saturday
Sunday
Enter fullscreen mode Exit fullscreen mode

4. A Practical Example: Weekly Task Manager

Let’s build a Weekly Task Manager. The program will:

  1. Store tasks for each day of the week.
  2. Allow the user to view or update tasks.
  3. Display all tasks for the week.

Step 1: Create the Array

We’ll use a string array to store tasks for each day.

string[] tasks = new string[7]; // 7 days in a week
Enter fullscreen mode Exit fullscreen mode

Step 2: Initialize with Default Tasks

Let’s initialize the array with some default tasks:

tasks[0] = "Gym in the morning";
tasks[1] = "Team meeting";
tasks[2] = "Work on project report";
tasks[3] = "Grocery shopping";
tasks[4] = "Dinner with friends";
tasks[5] = "Family outing";
tasks[6] = "Relax and read a book";
Enter fullscreen mode Exit fullscreen mode

Step 3: Build the Menu

The program will display a menu for the user to:

  1. View tasks.
  2. Update tasks.
  3. Display all tasks.

Step 4: Implement the Program

Here’s the full code:

using System;

class WeeklyTaskManager
{
    static void Main()
    {
        // Initialize tasks
        string[] tasks = {
            "Gym in the morning",
            "Team meeting",
            "Work on project report",
            "Grocery shopping",
            "Dinner with friends",
            "Family outing",
            "Relax and read a book"
        };

        while (true)
        {
            Console.WriteLine("\n=== Weekly Task Manager ===");
            Console.WriteLine("1. View Task");
            Console.WriteLine("2. Update Task");
            Console.WriteLine("3. Display All Tasks");
            Console.WriteLine("4. Exit");
            Console.Write("Choose an option: ");
            int option = int.Parse(Console.ReadLine());

            if (option == 4) break;

            switch (option)
            {
                case 1:
                    ViewTask(tasks);
                    break;
                case 2:
                    UpdateTask(tasks);
                    break;
                case 3:
                    DisplayAllTasks(tasks);
                    break;
                default:
                    Console.WriteLine("Invalid option. Please try again.");
                    break;
            }
        }
    }

    static void ViewTask(string[] tasks)
    {
        Console.Write("Enter the day number (1 for Monday, 7 for Sunday): ");
        int day = int.Parse(Console.ReadLine()) - 1;

        if (day >= 0 && day < tasks.Length)
        {
            Console.WriteLine($"Task for {GetDayName(day)}: {tasks[day]}");
        }
        else
        {
            Console.WriteLine("Invalid day number.");
        }
    }

    static void UpdateTask(string[] tasks)
    {
        Console.Write("Enter the day number (1 for Monday, 7 for Sunday): ");
        int day = int.Parse(Console.ReadLine()) - 1;

        if (day >= 0 && day < tasks.Length)
        {
            Console.Write($"Enter the new task for {GetDayName(day)}: ");
            tasks[day] = Console.ReadLine();
            Console.WriteLine("Task updated successfully.");
        }
        else
        {
            Console.WriteLine("Invalid day number.");
        }
    }

    static void DisplayAllTasks(string[] tasks)
    {
        Console.WriteLine("\n=== Weekly Tasks ===");
        for (int i = 0; i < tasks.Length; i++)
        {
            Console.WriteLine($"{GetDayName(i)}: {tasks[i]}");
        }
    }

    static string GetDayName(int index)
    {
        string[] daysOfWeek = { "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday" };
        return daysOfWeek[index];
    }
}
Enter fullscreen mode Exit fullscreen mode

How It Works

  1. View Task:

    • User inputs a day number.
    • Program retrieves and displays the task for that day.
  2. Update Task:

    • User inputs a day number and a new task.
    • Program updates the corresponding array element.
  3. Display All Tasks:

    • The program iterates through the array and prints each task with its day.

Sample Output

Menu:

=== Weekly Task Manager ===
1. View Task
2. Update Task
3. Display All Tasks
4. Exit
Choose an option:
Enter fullscreen mode Exit fullscreen mode

View Task:

Input: 1

Output: Task for Monday: Gym in the morning

Update Task:

Input: 2, then 7, then Plan next week

Output: Task updated successfully.

Display All Tasks:

=== Weekly Tasks ===
Monday: Gym in the morning
Tuesday: Team meeting
Wednesday: Work on project report
Thursday: Grocery shopping
Friday: Dinner with friends
Saturday: Family outing
Sunday: Plan next week
Enter fullscreen mode Exit fullscreen mode

Key Takeaways

  • Arrays are a great choice for managing fixed-size, ordered data.
  • Use foreach for enumeration and square brackets ([]) for accessing and modifying elements.
  • Arrays can power real-world applications like task managers, schedules, and more.

Top comments (0)