Why arrays are needed in C - Performance Analysis
We want to see how using arrays affects the time it takes to handle many items.
How does the program's work grow when we store data in arrays?
Analyze the time complexity of the following code snippet.
#include <stdio.h>
int main() {
int numbers[5] = {10, 20, 30, 40, 50};
for (int i = 0; i < 5; i++) {
printf("%d\n", numbers[i]);
}
return 0;
}
This code stores five numbers in an array and prints each one in order.
Look at what repeats in the code.
- Primary operation: Accessing and printing each number in the array.
- How many times: The loop runs 5 times, once for each number.
Imagine if the array had more numbers.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 times accessing and printing |
| 100 | 100 times accessing and printing |
| 1000 | 1000 times accessing and printing |
As the number of items grows, the work grows in the same way, one by one.
Time Complexity: O(n)
This means the time to finish grows directly with how many items are in the array.
[X] Wrong: "Accessing any item in an array takes longer if the array is bigger."
[OK] Correct: Accessing any single item by its position in an array is very fast and takes the same time no matter the size.
Understanding how arrays let us handle many items quickly is a key skill. It shows you know how data is stored and accessed efficiently.
"What if we used a linked list instead of an array? How would the time complexity for accessing items change?"