Arrays and linked lists are both ways to store multiple items. Why does accessing an element by its position in an array usually take less time than in a linked list?
Think about how memory addresses work and how the computer finds an element's location.
Arrays store elements one after another in memory. This lets the computer calculate the exact address of any element using its index, so it can jump directly to it. Linked lists store elements scattered in memory with pointers, so the computer must follow links one by one.
Consider this C code that inserts elements into an array and prints them:
int arr[5]; arr[0] = 10; arr[1] = 20; arr[2] = 30; for(int i = 0; i < 3; i++) { printf("%d ", arr[i]); }
Look at how many elements are assigned and how many are printed.
The code assigns values to the first three elements and prints only those three. So the output is the three assigned values separated by spaces.
Look at this C code snippet:
int arr[3] = {1, 2, 3};
printf("%d", arr[3]);What happens when this code runs?
int arr[3] = {1, 2, 3}; printf("%d", arr[3]);
Remember how array indexing works in C and what happens if you access beyond the declared size.
Arrays in C are zero-indexed, so valid indices are 0 to 2 for arr[3]. Accessing arr[3] goes beyond the array and causes undefined behavior, which can lead to unexpected output or crashes.
Consider this C code:
int arr[5] = {1, 2};
for(int i = 0; i < 5; i++) {
printf("%d ", arr[i]);
}What will be printed?
int arr[5] = {1, 2}; for(int i = 0; i < 5; i++) { printf("%d ", arr[i]); }
Think about how C initializes array elements not explicitly set.
When an array is partially initialized, the remaining elements are set to zero automatically in C.
Why do programmers use arrays instead of just many separate variables?
Think about managing many related pieces of data efficiently.
Arrays let you group many items under one name and access each by its index. This is easier than naming many separate variables and writing repetitive code.
