Resources | Subject Notes | Computer Science
An array is a fundamental data structure in computer science used to store a collection of elements of the same data type. These elements are stored in contiguous memory locations, allowing for efficient access using an index.
n-1
, where n
is the number of elements).array[index]
).In many programming languages, arrays are declared with a specific data type and size. The size is typically specified during declaration. Here's an example in a generic syntax:
data_type array_name[array_size];
Arrays can be initialized with values during declaration:
data_type array_name[array_size] = {value1, value2, value3, ...};
Elements in an array are accessed using their index. The index represents the position of the element within the array, starting from 0 for the first element.
The value of an element at a given index can be retrieved using the array name and the index enclosed in square brackets.
For example, if myArray
is an array of integers and myArray[2]
, it accesses the third element (index 2) of the array.
Operation | Description |
---|---|
Access | Retrieving the value of an element at a specific index. |
Assignment | Modifying the value of an element at a specific index. |
Iteration (Looping) | Processing each element of the array using a loop (e.g., for loop, while loop). |
Searching | Finding a specific element within the array. |
Sorting | Arranging the elements of the array in a specific order (e.g., ascending, descending). |
Arrays can be extended to multiple dimensions to store collections of collections. A two-dimensional array can be thought of as a table of values.
A two-dimensional array is declared with two indices: one for the row and one for the column.
data_type two_dimensional_array[rows][columns];
Arrays are often used with various algorithms. Some common examples include: