Skip to study material
← Question index

QUESTION 06 · Array Basics

Explain array subscripts, valid bounds and off-by-one errors.

5 marks

Answer in brief

A subscript is the integer expression inside brackets that selects an array element. Valid indices must remain within the array’s bounds.

Indexing example

For int a[4] = {10, 20, 30, 40};, a[0] is 10, a[2] is 30 and a[3] is 40. An index can be a variable or expression, such as a[i] or a[i + 1], when its resulting value is valid.

Correct loop

for (int i = 0; i < n; ++i) {
    printf("%d\n", a[i]);
}

Off-by-one mistake

Using i <= n instead of i < n reaches a[n] when n is the array’s logical length and capacity. That extra iteration is invalid for an array with exactly n elements. A one-based position shown to a student is different from a zero-based index: position 1 corresponds to index 0.

Bounds checks

  1. Check that the input count does not exceed the actual capacity.
  2. Check that an index is non-negative before using it.
  3. Check that the index is less than the number of elements allowed for the operation.
  4. For a[i + 1], make sure the next element exists too.

Important points

C does not promise a runtime error message for an invalid subscript. Reading or writing outside bounds has undefined behaviour and can corrupt unrelated data. A pointer may be formed one past an array in certain permitted operations, but it must not be dereferenced there. In this unit, simply restrict element access to valid indices.

Complexity

A valid direct access uses O(1) time in the usual array model. Checking a fixed set of bounds also uses O(1); it does not require traversing the array.

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 →