Array Declaration and Initialization in DSA C - Time & Space Complexity
When we create and fill an array, we want to know how long it takes as the array gets bigger.
We ask: How does the time to set up the array grow when the number of elements grows?
Analyze the time complexity of the following code snippet.
int n = 5;
int arr[5];
for (int i = 0; i < n; i++) {
arr[i] = i * 2;
}
This code creates an array of size 5 and fills it with values by multiplying the index by 2.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The for-loop that assigns values to each array element.
- How many times: It runs once for each element, so n times.
As the array size grows, the number of assignments grows the same way.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 assignments |
| 100 | 100 assignments |
| 1000 | 1000 assignments |
Pattern observation: The time grows directly with the number of elements; doubling n doubles the work.
Time Complexity: O(n)
This means the time to fill the array grows in a straight line with the number of elements.
[X] Wrong: "Declaring an array takes no time or is instant regardless of size."
[OK] Correct: While declaration reserves space quickly, initializing each element takes time proportional to the array size.
Understanding how array setup time grows helps you explain efficiency clearly and shows you know how data size affects performance.
"What if we initialize the array with a fixed value instead of a calculation? How would the time complexity change?"
