Single-dimensional array declaration in C Sharp (C#) - Time & Space Complexity
When we declare a single-dimensional array, we want to know how the time to create it changes as the array size grows.
We ask: How does the work needed to set up the array grow when the array gets bigger?
Analyze the time complexity of the following code snippet.
int n = 1000;
int[] numbers = new int[n];
for (int i = 0; i < n; i++)
{
numbers[i] = 0;
}
This code creates an array of size n and sets each element to zero.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The
forloop that sets each element in the array. - How many times: It runs exactly
ntimes, once for each element.
As the array size n grows, the number of steps to set elements grows the same way.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 steps to set elements |
| 100 | 100 steps to set elements |
| 1000 | 1000 steps to set elements |
Pattern observation: The work grows directly in proportion to the array size.
Time Complexity: O(n)
This means the time to set up the array grows linearly as the array gets bigger.
[X] Wrong: "Declaring an array is instant and does not depend on size."
[OK] Correct: Even though the array variable is declared quickly, initializing each element takes time proportional to the array size.
Understanding how array creation time grows helps you explain memory setup and initialization in real programs.
"What if we removed the loop that sets elements to zero? How would the time complexity change?"