Imagine you want to store the scores of 5 players in a game. Why is using an array better than using 5 separate variables?
Think about how you would handle many similar pieces of data together.
Arrays group multiple values under one name, so you can easily access and process them using loops. This is simpler than managing many separate variables.
Look at this code and choose the output it produces.
int[] numbers = {10, 20, 30, 40}; int sum = 0; for (int i = 0; i < numbers.Length; i++) { sum += numbers[i]; } Console.WriteLine(sum);
Think about what the loop does with each number in the array.
The loop adds each number in the array to sum: 10 + 20 + 30 + 40 = 100.
What error does this code cause when run?
int[] values = new int[3]; values[0] = 5; values[1] = 10; values[2] = 15; values[3] = 20; Console.WriteLine(values[3]);
Check the size of the array and the index used.
The array has size 3, so valid indexes are 0, 1, and 2. Accessing index 3 causes an IndexOutOfRangeException.
Choose the correct way to declare and initialize an integer array with values 1, 2, and 3 in C#.
Remember the syntax for array initialization in C#.
Option A uses the correct syntax: type[], new keyword, and curly braces for values.
What is the length of the array result after running this code?
int[] baseArray = {2, 4, 6}; int[] result = new int[baseArray.Length * 2]; for (int i = 0; i < baseArray.Length; i++) { result[i] = baseArray[i]; result[i + baseArray.Length] = baseArray[i] * 2; }
Look at how the size of result is set and how the loop fills it.
The result array is created with double the length of baseArray, so it has 6 items.