An array is a collection of elements of the same type, stored in a contiguous block of memory and accessible by an index. Arrays provide fast random access to elements and are one of the most widely used data structures in computing.
// Pseudocode
let a = new Array of length 5
// Initialize
for i from 0 to 4:
a[i] = 0
// Access and update
x = a[2] // read
a[2] = x + 10 // write
Accessing or updating an element by index is O(1). Accessing outside the valid range (e.g., a[-1] or a[n]) is an out-of-bounds error.
// Index-based loop
for i from 0 to n-1:
visit(a[i])
// Enhanced/for-each (conceptual)
for value in a:
visit(value)
Sequential iteration is cache-friendly and typically very fast.
// 2D indexing (row, col)
value = m[r][c]
// Traversal (row-major friendly)
for r from 0 to R-1:
for c from 0 to C-1:
visit(m[r][c])
For performance-sensitive code, align traversal with memory layout (row-major vs. column-major) to maximize cache locality.
// Aliasing example
b = a // b and a refer to the same array
b[0] = 42 // a[0] is now 42 as well
// Sum all elements
sum = 0
for i from 0 to n-1:
sum += a[i]
// Reverse in-place
left = 0
right = n - 1
while left < right:
swap(a[left], a[right])
left += 1
right -= 1
// Remove consecutive duplicates (in-place, assuming sorted)
if n > 0:
write = 1
for read from 1 to n-1:
if a[read] != a[read - 1]:
a[write] = a[read]
write += 1
// first 'write' elements are unique