Consider the following piece of code. What will be the space required for this…
2023
Consider the following piece of code. What will be the space required for this code? (Assume sizeof(int) = 2 bytes.)
int sum (int A[], int n)
{
int sum = 0, i;
for (i = 0; i < n; i++)
sum = sum + A[i];
return sum;
}- A.
2n + 8
- B.
2n + 4
- C.
2n + 2
- D.
2n
Attempted by 6 students.
Show answer & explanation
Correct answer: A
Concept: The total space required by a piece of code is the space taken by the data it operates on (here, the input array) plus the space taken by every parameter and local variable declared in the function, each sized according to the given sizeof(int). When an array is passed to a C function, the function actually receives only a reference (pointer) to it — for this class of exam question the standard convention is to size that pointer/reference the same as sizeof(int) when no separate pointer size is stated — so both the array's own element storage AND the pointer that refers to it must be counted separately toward the total.
Application:
The array A holds n elements, each an int of 2 bytes, so the array's element storage is 2n bytes.
The parameter A itself is stored as a pointer/reference to the array, occupying 2 bytes (pointer size taken equal to int size here).
The parameter n is an int, occupying 2 bytes.
The local variable sum is an int, occupying 2 bytes.
The local variable i is an int, occupying 2 bytes.
Adding the four 2-byte scalar items: 2 + 2 + 2 + 2 = 8 bytes.
Total space = array storage + scalar storage = 2n + 8 bytes.
Cross-check: As an independent check, take n = 0 (an empty array): the loop never executes, so no array storage is needed, but the four scalar slots (pointer A, n, sum, i) still exist in the stack frame, giving 2(0) + 8 = 8 bytes — consistent with the formula. Among the options, only 2n + 8 accounts for all four scalar slots together with the array storage; the others omit one or more of them and would undercount the space at n = 0 as well.
Hence the space required is 2n + 8 bytes.