QUESTION 05 · Array Basics
What is the valid index range for int a[10]?
2 marksAnswer
The valid indices are 0 through 9.
- a[0] is the first element.
- a[10] is outside this array and must not be accessed.
QUESTION 05 · Array Basics
The valid indices are 0 through 9.
QUESTION 06 · Array Basics
A subscript is the integer expression inside brackets that selects an array element. Valid indices must remain within the array’s bounds.
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.
for (int i = 0; i < n; ++i) {
printf("%d\n", a[i]);
}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.
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.
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 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