What is an Array?
An array is a data structure that stores a fixed-size, ordered collection of elements of the same type. Each element in an array is identified by an index or position.
Imagine an array as a row of boxes where each box holds a value, and each box is labeled with an index starting from 0.
Why Do We Use Arrays?
- To group similar data elements together.
- To access elements quickly using indexes.
- To perform batch operations like sorting, filtering, and iterating.
Declaring and Initializing an Array
Here’s how you can declare and initialize an array in pseudocode:
Declare array of size 5
array = [10, 20, 30, 40, 50]
This array holds 5 integers. Index starts from 0 and goes to 4.
Accessing Array Elements
You can access or modify elements using their index:
value = array[2] // Accesses the 3rd element which is 30
array[4] = 100 // Changes the 5th element to 100
Output:
value = 30 array = [10, 20, 30, 40, 100]
Question:
What happens if you try to access array[5]
in the above example?
Answer: You’ll get an error or unexpected behavior because index 5 is out of bounds. The valid indices are 0 to 4 for an array of size 5.
Iterating Through an Array
To perform operations on each element, you can loop through the array:
for i from 0 to length of array - 1 do
print(array[i])
end for
Output:
10 20 30 40 100
Common Operations on Arrays
1. Finding the Maximum Element
max = array[0]
for i from 1 to length of array - 1 do
if array[i] > max then
max = array[i]
end if
end for
print(max)
Output:
100
2. Calculating the Sum of All Elements
sum = 0
for i from 0 to length of array - 1 do
sum = sum + array[i]
end for
print(sum)
Output:
200
Question:
Can an array hold elements of different types?
Answer: In most programming languages, arrays are homogeneous, meaning all elements should be of the same type (like all integers or all strings).
Limitations of Arrays
- Fixed size: You must define the size upfront.
- Inefficient insertions and deletions (especially in the middle).
Tip:
If you need a dynamic data structure that grows or shrinks, consider using a List or Dynamic Array instead.
Summary
- Arrays store data in a fixed-size, indexed format.
- Elements are accessed using indices, starting from 0.
- They are ideal for fast lookup but less efficient for insertions/deletions.