QUESTION 16 · Arrays and Functions
Explain passing a one-dimensional array to a function with its length.
5 marksAnswer in brief
A function can process an array when it receives access to its elements and enough information to keep its accesses within bounds.
Function interface
long long total(const int a[], int n);
Meaning
In a parameter declaration, const int a[] is adjusted to const int *a. The function receives a pointer value identifying the first element. The array contents are not automatically copied. n states how many elements the function is allowed to read. const prevents modification through this parameter’s element access.
Example trace
main holds 4, 5 and 6 and calls total(a, 3). The function visits a[0], a[1] and a[2], adding them to its local accumulator. It returns 15. main prints the result. The array remains unchanged because this function only reads it.
Important points
- Pass a valid length that fits the actual object.
- Do not use sizeof a / sizeof a[0] inside this adjusted parameter to discover the caller’s array length.
- A non-const int parameter written as int a[] can be used to modify the caller’s elements.
- C still passes a value: the pointer is copied, while the elements remain in the original array.
Complexity
The function reads n elements once, giving O(n) time. It does not build a second array; only a sum and counter are added, giving O(1) auxiliary space. Copying a pointer argument does not mean copying n elements.
C program and output
/* CodeBhavya | PPS AR25 | Learning example */
#include <stdio.h>
long long total(const int a[], int n)
{
long long sum = 0;
for (int i = 0; i < n; ++i) { sum += a[i]; }
return sum;
}
int main(void)
{
int a[3] = {4, 5, 6};
printf("Total = %lld\n", total(a, 3));
return 0;
}
Sample input and output
This example uses values already written in the program.
Output
Total = 15
Related exam questions
Related questions in the array function arguments category from the supplied papers. The marks below are the printed allocations, including any combined subquestion.
- July 2021 · Q7 · 15 marks
Illustrate passing arrays to functions with a relevant example program.
Paper P04 · page 1 - January/February 2024 · Q9(b) · 5 marks
Explain passing an entire array as an argument to a function, with an example.
Paper P10 · page 2
View this category in the exam question bank →