Resources | Subject Notes | Computer Science
An array is a fundamental data structure in computer science used to store a collection of items of the same data type. These items are stored in contiguous memory locations, allowing for efficient access. Arrays are a core concept for managing and processing sets of data.
Think of an array as a row of boxes, where each box can hold a value of the same type (e.g., integers, characters, floating-point numbers). Each box has a unique index, which we use to access the value stored in that box.
In most programming languages, arrays are declared with a specific data type and a size (number of elements). Here's how you might declare and initialize an array in a typical syntax:
# Python example
my_array = [10, 20, 30, 40, 50]
# This declares an array named 'my_array' containing 5 integer elements.
// Java example
int[] myArray = new int[5];
// This declares an integer array named 'myArray' with a size of 5.
Elements in an array are accessed using their index. Array indices typically start from 0. So, the first element is at index 0, the second at index 1, and so on.
The syntax for accessing an element varies slightly between languages:
Common operations performed on arrays include:
Here's a simple example of how to iterate through an array using a loop:
# Python example
my_array = [1, 2, 3, 4, 5]
for element in my_array:
print(element)
// Java example
int[] myArray = {1, 2, 3, 4, 5};
for (int i = 0; i < myArray.length; i++) {
System.out.println(myArray[i]);
}
Operation | Syntax (Python) | Syntax (Java) |
---|---|---|
Access Element | my_array[index] |
myArray[index] |
Modify Element | my_array[index] = new_value |
myArray[index] = new_value |
Access Length | len(my_array) |
myArray.length |
Arrays are used extensively in computer science for various applications, including:
When working with arrays, it's important to be mindful of array bounds. Accessing an element outside the valid range of indices can lead to errors. In some languages, this will cause a runtime error. Understanding array bounds is crucial for writing robust and reliable code.