Logo

dev-resources.site

for different kinds of informations.

Introduction to Arrays

Published at
11/30/2024
Categories
csharp
arrays
collections
dotnet
Author
moh_moh701
Categories
4 categories in total
csharp
open
arrays
open
collections
open
dotnet
open
Author
10 person written this
moh_moh701
open
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.
arrays Article's
30 articles in total
Favicon
lodash._merge vs Defu
Favicon
Leetcode — 2942. Find Words Containing Character
Favicon
Leetcode — 3289. The Two Sneaky Numbers of Digitville
Favicon
Introduction to Arrays
Favicon
Growing Pains: How Dynamic Arrays Handle New Elements ?
Favicon
Array and Object Access
Favicon
How do we sort an Array in Javascript without Sort function?
Favicon
Leetcode — Top Interview 150–169. Majority Element
Favicon
arrayToDict function in tRPC source code
Favicon
mismatch() and compare() in Java
Favicon
Create a unique array using Set() in JavaScript.
Favicon
Shifting Non-Zero Values Right : A Common Array Interview Problem-2
Favicon
Shifting Non-Zero Values Left: A Common Array Interview Problem-1
Favicon
Understanding Array Basics in Java: A Simple Guide
Favicon
Data Structures: Arrays
Favicon
Just uploaded a new video on arrays in Java Dive in and check it out now!
Favicon
Pointers and Arrays
Favicon
Arrays de strings
Favicon
Tente Isto 5-1: Classifique um array
Favicon
Arrays multidimensionais
Favicon
Arrays
Favicon
How to sort correctly arrays in JavaScript?
Favicon
Arrays
Favicon
Simple way to obtain largest Number in an array or slice in golang
Favicon
⭐️Exploring the Dynamic World of JavaScript🚀
Favicon
How to Master Joining and Splitting Numpy Arrays: A Comprehensive Guide
Favicon
Understanding NumPy: Datatypes, Memory Storage, and Structured Arrays.
Favicon
PHP - arrays e valores como chave
Favicon
Array Methods: TypeScript vs C# 🧮
Favicon
NumPy Unleashed: Exploring the Power of Special Arrays

Featured ones: