Arrays are foundational for organizing data in computer programs.
Different programming languages may use different conventions for indexing.
Notable figure: Donald Knuth, expert on algorithms, humorously remarks on varying indexing practices.
Definition: A data structure that holds multiple values of the same type.
Access: Indexing allows ordering by assigning positions to elements.
Terminology: Variables can hold one value, while arrays hold collections of related values.
An array declaration includes:
Type: Specifies data type of stored values.
Identifier: The name used to reference the array.
Size: Indicates how many values the array can hold.
Example: float studentOne_quizScores[6];
Memory Allocation: Compilers allocate arrays in a single block based on size and type at compile time.
Distinction between referring to the entire array and individual elements.
Indices start at zero—a convention in many languages:
Indexing example for accessing quiz scores: studentOne_quizScores[1] = 20;
Special property: Elements are sequentially stored in memory.
Valid indices range from 0
to size - 1
.
No automatic bounds checking in C++—invalid indices lead to memory access errors, potentially causing crashes.
Example demonstrating unsafe access can lead to undefined behavior.
The off-by-one error is common, particularly when writing loops.
Correct usage: for (int i = 0; i < SIZE; i++)
Initialization: Arrays need proper initialization; uninitialized elements hold garbage values.
Methods of initialization include:
Individual assignment during operations.
Assignment during declaration with initialization lists.
Example: string months[12] = {"Jan", "Feb", ...};
Arrays often processed with loops, typically for
loops, to iterate over each element.
Operations examples: Summation, averaging values, and finding extremes all involve iterating through the elements.
Parallel arrays maintain separate but related data sets using the same index.
Example: One array holds quiz one scores, another holds quiz two scores, linked by the student's index.
Defined with two sets of brackets to represent rows and columns, for example: double scores[3][4];
Use case: Can be visualized as tables of data where each element requires both row and column indices.
A standard template library container that provides dynamic arrays (vectors) with additional capabilities:
Allows resizing during runtime, can grow as needed.
Provides random access like arrays but includes bounds checking through methods such as .at()
.
Vectors can be accessed through square bracket notation or .at()
which provides error handling for invalid indices.
Vectors support increasing size with push_back()
and retrieving the size using .size()
, among others.
Can also empty a vector using clear()
, removing all elements efficiently.