Arrays and linked lists are both ways to store multiple items. Why can arrays give you an item faster when you know its position?
Think about how memory addresses work and how knowing the start helps.
Arrays store elements one after another in memory. This means if you know the start address and the size of each element, you can calculate exactly where any element is. Linked lists store elements scattered in memory with pointers, so you must follow links one by one.
Consider this C# code that fills an array with numbers. What will be printed?
int[] numbers = new int[5]; for (int i = 0; i < numbers.Length; i++) { numbers[i] = i * 2; } for (int i = 0; i < numbers.Length; i++) { Console.Write(numbers[i] + " "); }
Look at how each element is assigned inside the loop.
The loop assigns each element the value of its index multiplied by 2. So index 0 gets 0, index 1 gets 2, index 2 gets 4, and so on.
What error will this C# code produce and why?
int[] arr = new int[3] {1, 2, 3}; int x = arr[3];
Remember array indexes start at 0 and go up to length-1.
The array has indexes 0, 1, and 2. Accessing index 3 is outside the valid range, causing an IndexOutOfRangeException.
Imagine you want to store a fixed number of student grades. Why is an array a good choice compared to other data structures?
Think about memory allocation and the number of items you want to store.
Arrays allocate a fixed size in memory, which is efficient when you know how many items you need to store. This avoids overhead of dynamic resizing or pointers.
Why do we need arrays instead of just using many separate variables to store multiple values?
Think about managing many related values in your code.
Using many separate variables is hard to manage and does not scale. Arrays let you group many values under one name and access them by position, making code easier to write and maintain.
