QUESTION 09 · Array Basics
What is array traversal?
2 marksAnswer
Traversal visits the array elements in a chosen order to perform an operation on each.
- A forward traversal usually uses indices 0 through n - 1.
- A sum accumulator starts at zero.
QUESTION 09 · Array Basics
Traversal visits the array elements in a chosen order to perform an operation on each.
QUESTION 10 · Array Basics
Array traversal visits elements one by one. The same loop pattern can display values, calculate a sum or count values satisfying a condition.
For the list 4, -1 and 7, sum starts at 0. After index 0 it is 4. After index 1 it is 3. After index 2 it is 10. The loop finishes after every valid element has contributed exactly once.
Starting at index 1 would omit the first element. Using i <= n would attempt an extra access. The loop condition i < n covers exactly n elements when i starts at zero and increases by one. The list need not be sorted for a sum.
The sample uses long long for sum and %lld to print it. With at most 20 inputs of magnitude at most 10000, the total fits that type’s guaranteed range. A general implementation must choose a type and supported bounds suitable for its largest possible total.
The loop performs one addition for every element, so n elements give O(n) time. Input reading is also O(n), leaving the total linear. Apart from the array, only a count, counter and accumulator are needed: O(1) auxiliary space. Traversal is not a separate copy of the array.
/* CodeBhavya | PPS AR25 | Learning example */
#include <stdio.h>
int main(void)
{
int n, a[20];
if (scanf("%d", &n) != 1 || n < 1 || n > 20) {
puts("Unsupported input"); return 1;
}
for (int i = 0; i < n; ++i) {
if (scanf("%d", &a[i]) != 1 || a[i] < -10000 || a[i] > 10000) {
puts("Unsupported input"); return 1;
}
}
long long sum = 0;
for (int i = 0; i < n; ++i) { sum += a[i]; }
printf("Sum = %lld\n", sum);
return 0;
}3
4 -1 7Sum = 10Related questions in the arrays category from the supplied papers. The marks below are the printed allocations, including any combined subquestion.
Write an algorithm to sum all elements in an array and find its time complexity.
Paper P02 · page 2What is an array? Describe declaration and initialisation of one- and two-dimensional arrays.
Paper P03 · page 1