<aside> Arrays are fundamental data structures that store collections of elements of the same type. They provide efficient ways to manage and access multiple related values.
</aside>
An array is a collection of variables of the same datatype, organized by index numbers starting at 0.
<aside> 💡 Key Concept: Arrays are zero-based, meaning the first element is at index 0. An array with length 7 has indices 0 through 6.
</aside>
// Method 1: Declare with size
int[] numbers = new int[9];
// Method 2: Declare with values
int[] numbers = { 4, 5, 6, 1, 2, 3, -2, -1, 0 };
// Method 3: Declare and initialize later
int[] scores;
scores = new int[] { 85, 92, 78, 95, 88 };
<aside> Always use plural names for arrays to indicate they contain multiple values (e.g., numbers, names, scores)
</aside>
Special shorthand for creating character arrays:
// Quick character array initialization
char[] uppercaseLetters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".ToCharArray();
char[] lowercaseLetters = "abcdefghijklmnopqrstuvwxyz".ToCharArray();
char[] digits = "0123456789".ToCharArray();
char[] specialCharacters = "!@#$%^&*()-_=+[]{}|;:'\\",.<>?/".ToCharArray();
int[] numbers = { 1, 2, 3, 4, 5 };
// Reading value
int value = numbers[2]; // Gets 3
// Setting value
numbers[2] = 10; // Changes 3 to 10
// Getting last element
int last = numbers[numbers.Length - 1];
There are several ways to iterate through arrays:
for (int i = 0; i < numbers.Length; i++)
{
Console.WriteLine(numbers[i]);
}
foreach (int number in numbers)
{
Console.WriteLine(number);
}
<aside> ⚠️ Common Pitfalls: • Accessing index out of bounds • Forgetting arrays are zero-based • Not initializing array elements • Trying to resize fixed arrays
</aside>