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:
- What arrays are.
- How to create and initialize them.
- Accessing, modifying, and enumerating array elements.
- 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 at1
, and so on.
2. Creating and Initializing Arrays
Example: Storing Days of the Week
string[] daysOfWeek = { "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday" };
Here:
-
string[]
specifies that the array stores strings. -
{ ... }
contains the array’s initial values.
Accessing Items
Console.WriteLine(daysOfWeek[0]); // Output: Monday
Modifying Items
daysOfWeek[2] = "Weds"; // Updates Wednesday to Weds
3. Enumerating an Array
You can iterate through an array using a foreach
loop:
Example
foreach (string day in daysOfWeek) { Console.WriteLine(day); }
This prints:
Monday Tuesday Wednesday Thursday Friday Saturday Sunday
4. A Practical Example: Weekly Task Manager
Let’s build a Weekly Task Manager. The program will:
- Store tasks for each day of the week.
- Allow the user to view or update tasks.
- 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
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";
Step 3: Build the Menu
The program will display a menu for the user to:
- View tasks.
- Update tasks.
- 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]; } }
How It Works
-
View Task:
- User inputs a day number.
- Program retrieves and displays the task for that day.
-
Update Task:
- User inputs a day number and a new task.
- Program updates the corresponding array element.
-
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:
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
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)