This content originally appeared on DEV Community and was authored by mohamed Tayel
Meta Description: Learn all about arrays in C# with hands-on examples. Understand how to create, populate, and iterate through single and multidimensional arrays. Explore easy, medium, and advanced assignments to deepen your knowledge of array operations and apply them effectively in your C# projects
Arrays are a fundamental data structure in C#. They allow you to store multiple values of the same type in a single collection. This makes them ideal for scenarios where you need to manage multiple items, such as employee IDs, a list of products, or even song playlists.
In C#, arrays are zero-based, meaning the first element has an index of 0
. Arrays have a fixed size, which is defined at the time of their creation. This fixed nature makes them very efficient when dealing with a known number of items, but they lack the flexibility to grow dynamically like collections. Arrays are also reference types, meaning they are stored on the heap, and the array variable holds a reference to this memory location.
What Are Arrays?
An array is a collection of items of the same type. You can think of it as a container that holds a specific number of values, all of the same type, accessible by an index. Let’s start with a few clear examples, including how to fill arrays.
Example 1: Creating and Filling an Array of Primitive Types
In this example, we will create an array of integers and then add values to it:
// Step 1: Declare and create an array of 4 integers
int[] employeeIds = new int[4];
// Step 2: Fill the array with values
employeeIds[0] = 101; // Assign value to the first position
employeeIds[1] = 102; // Assign value to the second position
employeeIds[2] = 103; // Assign value to the third position
employeeIds[3] = 104; // Assign value to the fourth position
// Step 3: Display the values in the array
for (int i = 0; i < employeeIds.Length; i++)
{
Console.WriteLine($"Employee ID at index {i}: {employeeIds[i]}");
}
-
Explanation:
- We first declare an array called
employeeIds
that can hold 4 integer values. - We then add values to each position in the array using their respective indices.
- Finally, we display the values using a
for
loop to iterate over each element.
- We first declare an array called
Output:
Employee ID at index 0: 101
Employee ID at index 1: 102
Employee ID at index 2: 103
Employee ID at index 3: 104
Example 2: Creating and Filling an Array of Custom Types
Arrays can also store custom types, such as employee objects. Suppose we have an Employee
class defined like this:
public class Employee
{
public string Name { get; set; }
public int Id { get; set; }
public void DisplayEmployeeDetails()
{
Console.WriteLine($"Employee ID: {Id}, Name: {Name}");
}
}
Now, let's create an array of Employee
objects and fill it:
// Step 1: Declare and create an array for 3 Employee objects
Employee[] employees = new Employee[3];
// Step 2: Create Employee objects and assign them to the array
employees[0] = new Employee() { Name = "Bethany", Id = 1 };
employees[1] = new Employee() { Name = "George", Id = 2 };
employees[2] = new Employee() { Name = "Alice", Id = 3 };
// Step 3: Display details of each employee using a foreach loop
foreach (Employee e in employees)
{
e.DisplayEmployeeDetails();
}
-
Explanation:
- We create an array called
employees
to hold threeEmployee
objects. - We then instantiate each employee and assign it to a position in the array.
- Finally, we use a
foreach
loop to iterate over the array and callDisplayEmployeeDetails
on each employee.
- We create an array called
Output:
Employee ID: 1, Name: Bethany
Employee ID: 2, Name: George
Employee ID: 3, Name: Alice
Example 3: Using Built-in Array Functionalities
Arrays come with several built-in functionalities that can make working with them easier, such as sorting, copying, and reversing.
-
Sorting an Array: You can use the
Array.Sort()
method to sort an array of integers.
int[] employeeIds = { 99, 1, 55, 84, 15 };
// Step 1: Sort the array
Array.Sort(employeeIds);
// Step 2: Display the sorted values
Console.WriteLine("Sorted Employee IDs:");
foreach (int id in employeeIds)
{
Console.WriteLine(id);
}
Explanation: The
Array.Sort()
method sorts the elements in ascending order.Output:
Sorted Employee IDs:
1
15
55
84
99
-
Copying an Array: You can create a copy of an array using the
CopyTo()
method.
int[] employeeIdsCopy = new int[employeeIds.Length];
employeeIds.CopyTo(employeeIdsCopy, 0); // Copies all elements from employeeIds to employeeIdsCopy
Console.WriteLine("Copied Employee IDs:");
foreach (int id in employeeIdsCopy)
{
Console.WriteLine(id);
}
Explanation: The
CopyTo()
method copies elements from theemployeeIds
array to the newemployeeIdsCopy
array starting from index0
.Output:
Copied Employee IDs:
1
15
55
84
99
-
Reversing an Array: You can reverse the order of elements using the
Array.Reverse()
method.
Array.Reverse(employeeIds); // Reverses the order of elements
Console.WriteLine("Reversed Employee IDs:");
foreach (int id in employeeIds)
{
Console.WriteLine(id);
}
Explanation: This reverses the
employeeIds
array, so the elements are displayed in reverse order.Output:
Reversed Employee IDs:
99
84
55
15
1
Assignments: Easy, Medium, and Difficult
Now that we have a solid understanding of how to create and work with arrays, let's explore some practical assignments at different levels of difficulty to solidify these concepts.
Assignment 1: Easy - Creating and Using an Array
Task: Create an array to store and display five fruit names.
Code:
// Step 1: Declare and create an array of fruits
string[] fruits = new string[5] { "Apple", "Banana", "Orange", "Grapes", "Mango" };
// Step 2: Display each fruit using a loop
for (int i = 0; i < fruits.Length; i++)
{
Console.WriteLine($"Fruit {i + 1}: {fruits[i]}");
}
-
Description:
- Create an array named
fruits
with five predefined fruit names. - Use a
for
loop to display each fruit.
- Create an array named
Expected Output:
Fruit 1: Apple
Fruit 2: Banana
Fruit 3: Orange
Fruit 4: Grapes
Fruit 5: Mango
Assignment 2: Medium - Dynamic Array Length
Task: Create an array of employee IDs with a length specified by the user.
Code:
Console.WriteLine("How many employee IDs would you like to register?");
int length = int.Parse(Console.ReadLine());
// Step 1: Declare and create an array with the specified length
int[] employeeIds = new int[length];
// Step 2: Fill the array with user input
for (int i = 0; i < length; i++)
{
Console.Write($"Enter employee ID {i + 1}: ");
employeeIds[i] = int.Parse(Console.ReadLine());
}
// Step 3: Display the registered employee IDs
Console.WriteLine("\nThe registered employee IDs are:");
for (int i = 0; i < length; i++)
{
Console.WriteLine($"Employee ID {i + 1}: {employeeIds[i]}");
}
-
Description:
- Ask the user for the number of employee IDs to register.
- Create an array of that length and fill it with the user-provided IDs.
- Display all the entered IDs.
Expected Output (example):
How many employee IDs would you like to register?
3
Enter employee ID 1: 101
Enter employee ID 2: 102
Enter employee ID 3: 103
The registered employee IDs are:
Employee ID 1: 101
Employee ID 2: 102
Employee ID 3: 103
Assignment 3: Difficult - Wage Calculation Using Arrays
Task: Calculate and display wages for employees. Allow the user to input employee names and hours worked, then compute wages.
**
Code**:
Console.WriteLine("How many employees do you have?");
int employeeCount = int.Parse(Console.ReadLine());
// Step 1: Declare and create an array of Employee objects
Employee[] employees = new Employee[employeeCount];
double hourlyRate = 15.0;
// Step 2: Populate the employee array with names and hours worked
for (int i = 0; i < employeeCount; i++)
{
Console.Write($"Enter name of employee {i + 1}: ");
string name = Console.ReadLine();
Console.Write($"Enter hours worked by {name}: ");
double hoursWorked = double.Parse(Console.ReadLine());
employees[i] = new Employee() { Name = name, Id = i + 1 };
employees[i].PerformWork(hoursWorked);
}
// Step 3: Display the wage report for each employee
Console.WriteLine("\nEmployee Wage Report:");
foreach (Employee e in employees)
{
e.DisplayEmployeeDetails();
e.ReceiveWage(hourlyRate);
}
-
Description:
- Ask the user for the number of employees.
- Create an array of
Employee
objects and populate it with names and hours worked. - Calculate and display the wages for each employee.
Expected Output (example):
How many employees do you have?
2
Enter name of employee 1: Alice
Enter hours worked by Alice: 40
Enter name of employee 2: Bob
Enter hours worked by Bob: 35
Employee Wage Report:
Employee ID: 1, Name: Alice
Worked for: 40 hours, Wage: $600.00
Employee ID: 2, Name: Bob
Worked for: 35 hours, Wage: $525.00
Conclusion
Arrays in C# are a powerful tool for storing and working with collections of data. They provide several built-in functionalities for sorting, copying, and reversing the data. By starting with these easy, medium, and difficult examples, you should now feel more comfortable creating, populating, and using arrays in practical scenarios. Practice these assignments, and soon you'll be able to use arrays effectively in your projects. For scenarios requiring more flexibility, consider using collections, which allow dynamic resizing.
This content originally appeared on DEV Community and was authored by mohamed Tayel
mohamed Tayel | Sciencx (2024-09-30T21:05:37+00:00) Mastering C# Fundamentals: Understanding Arrays. Retrieved from https://www.scien.cx/2024/09/30/mastering-c-fundamentals-understanding-arrays/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.