Arrays Explained in 8 Minutes - Data Structures for Beginners (C# Examples)
Video: Arrays Explained in 8 Minutes - Data Structures for Beginners (C# Examples) by Taught by Celeste AI - AI Coding Coach
Watch full page →Arrays Explained in 8 Minutes - Data Structures for Beginners (C# Examples)
Arrays are one of the most fundamental data structures in programming, providing a way to store multiple elements of the same type in a contiguous block of memory. In C#, arrays allow fast random access by index, making them ideal for scenarios where quick lookups are needed. This guide covers how to declare, initialize, and iterate over arrays, as well as the performance characteristics of common operations.
Code
// Declare and initialize an array of integers with 5 elements
int[] numbers = new int[5];
// Assign values to each element by index
numbers[0] = 10;
numbers[1] = 20;
numbers[2] = 30;
numbers[3] = 40;
numbers[4] = 50;
// Alternatively, initialize with values directly
int[] primes = { 2, 3, 5, 7, 11 };
// Access an element in O(1) time by index
int firstPrime = primes[0]; // 2
// Iterate through the array using a for loop
for (int i = 0; i < primes.Length; i++)
{
Console.WriteLine(primes[i]);
}
// Insertion or deletion requires shifting elements, which is O(n)
void InsertAt(int[] arr, int index, int value)
{
// Note: Arrays have fixed size, so this is conceptual
for (int i = arr.Length - 1; i > index; i--)
{
arr[i] = arr[i - 1]; // Shift elements right
}
arr[index] = value;
}
Key Points
- Arrays store elements contiguously in memory, enabling O(1) random access by index.
- In C#, arrays have a fixed size and must be initialized with a length or values upfront.
- Iterating over arrays is straightforward using loops, commonly for or foreach.
- Insertion and deletion in arrays are costly O(n) operations because elements must be shifted.
- Use arrays when you need fast access and fixed-size collections; consider other structures for dynamic resizing.