Resources | Subject Notes | Computer Science
Arrays are a fundamental data structure in computer science used to store a collection of elements of the same data type. They provide a way to organize and access multiple items under a single variable name. This topic is crucial for efficient data handling in programming.
An array is a contiguous block of memory locations allocated to store elements of the same type. Each element in an array is accessed using an index, which is a numerical value representing the position of the element within the array. Array indices typically start from 0.
In most programming languages, arrays are declared with a specific data type and a size. The size determines the maximum number of elements the array can hold. Initialization involves assigning values to the array elements.
# Declare an array of 5 integers my_array = [0, 0, 0, 0, 0] # Declare an array of characters with a size of 10 char_array = [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ']
Array elements are accessed using their index within square brackets `[]`. The index starts from 0 for the first element, 1 for the second, and so on.
my_array = [10, 20, 30, 40, 50] # Access the first element (index 0) first_element = my_array[0] # first_element will be 10 # Access the third element (index 2) third_element = my_array[2] # third_element will be 30
Common operations performed on arrays include:
my_array = [1, 2, 3, 4, 5] for i in range(len(my_array)): print(f"Element at index {i}: {my_array[i]}")
Arrays can be extended to create multidimensional arrays, such as 2D arrays (matrices). These are useful for representing tables or grids of data.
# A 2D array with 3 rows and 4 columns matrix = [ [1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12] ] # Accessing an element in the second row and third column (index 1, 2) element = matrix[1][2] # element will be 7
Array Index | Element Value |
---|---|
0 | $my\_array[0]$ |
1 | $my\_array[1]$ |
2 | $my\_array[2]$ |
3 | $my\_array[3]$ |
4 | $my\_array[4]$ |
Arrays are used in a wide variety of programming applications, including: