Skip to study material
← Question index

QUESTION 10 · Array Basics

Explain array traversal and write a program to find the sum of its elements.

5 marks

Answer in brief

Array traversal visits elements one by one. The same loop pattern can display values, calculate a sum or count values satisfying a condition.

Algorithm for a sum

  1. Read a valid count and its elements.
  2. Set sum to zero.
  3. For each index i from 0 through n - 1, add a[i] to sum.
  4. Display sum.

Worked trace

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.

Why the bounds matter

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.

Type choice

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.

Time and space complexity

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.

C program and output

/* 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;
}

Sample input and output

Input

3
4 -1 7

Output

Sum = 10

Related exam questions

Related questions in the arrays category from the supplied papers. The marks below are the printed allocations, including any combined subquestion.

  • March/April 2023 · Q11(b) · 5 marks

    Write an algorithm to sum all elements in an array and find its time complexity.

    Paper P02 · page 2
  • June 2022 · Q3(a) · 7 marks

    What is an array? Describe declaration and initialisation of one- and two-dimensional arrays.

    Paper P03 · page 1

View this category in the exam question bank →