Array initialization in C - Time & Space Complexity
When we create and fill an array, the time it takes depends on how many items we add.
We want to know how the work grows as the array size grows.
Analyze the time complexity of the following code snippet.
int arr[1000];
for (int i = 0; i < 1000; i++) {
arr[i] = 0;
}
This code sets each element of an array with 1000 items to zero.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Setting each array element to zero inside the loop.
- How many times: Exactly 1000 times, once for each element.
As the array size grows, the number of steps grows the same way.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 steps |
| 100 | 100 steps |
| 1000 | 1000 steps |
Pattern observation: Doubling the array size doubles the work needed.
Time Complexity: O(n)
This means the time to initialize grows directly with the number of elements.
[X] Wrong: "Initializing an array is instant no matter the size."
[OK] Correct: Each element must be set one by one, so bigger arrays take more time.
Understanding how array initialization scales helps you explain performance in real code.
"What if we initialize the array with a fixed value using a library function? How would the time complexity change?"