Bird
0
0
DSA Cprogramming~5 mins

Array Declaration and Initialization in DSA C - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Array Declaration and Initialization
O(n)
Understanding Time 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?

Scenario Under Consideration

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 Repeating Operations

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.
How Execution Grows With Input

As the array size grows, the number of assignments grows the same way.

Input Size (n)Approx. Operations
1010 assignments
100100 assignments
10001000 assignments

Pattern observation: The time grows directly with the number of elements; doubling n doubles the work.

Final Time Complexity

Time Complexity: O(n)

This means the time to fill the array grows in a straight line with the number of elements.

Common Mistake

[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.

Interview Connect

Understanding how array setup time grows helps you explain efficiency clearly and shows you know how data size affects performance.

Self-Check

"What if we initialize the array with a fixed value instead of a calculation? How would the time complexity change?"