An array is a data structure that can store a fixed-size sequence of elements, all of the same type, such as integers, floats, or strings. The elements in an array are stored in contiguous memory locations, and each element can be accessed using an index or a
Key.
Characteristics of an Array:
Fixed Size:
The size of an array is defined when the array is declared and cannot be changed dynamically (in most languages).
Homogeneous Elements:
All elements of an array must be of the same data type, such as all integers or all floating-point numbers.
Indexed Access:
Each element in an array is accessed by an index, starting from 0 in most programming languages. For example, the first element of an array `arr` is accessed using `arr[0]`.
Contiguous Memory Allocation:
Arrays store elements in adjacent memory locations, which allows for efficient access.
Types of Arrays:
1. One-dimensional (1D) Array:
A simple list of elements.
Example:
\[
\text{int arr[5] = \{1, 2, 3, 4, 5\};}
\]
2. Two-dimensional (2D) Array:
An array of arrays, which can be thought of as a table or matrix.
Example:
\[
\text{int matrix[3][3] = \{ \{1, 2, 3\}, \{4, 5, 6\}, \{7, 8, 9\} \};}
\]
3. Multi-dimensional Arrays:
Arrays with more than two dimensions, commonly used for complex data storage like images or matrices.
Example:
A simple one-dimensional array of integers in C would look like this:
\[
\text{int arr[] = \{5, 10, 15, 20, 25\};}
\]
To access the second element of the array, you would use the index:
\[
\text{arr[1]} = 10
\]
(The index starts at 0, so `arr[1]` refers to the second element.)
Summary:
An array is a collection of elements, all of the same data type, stored at contiguous memory locations, and accessed using an index.