⬅ Previous Topic
Recursion BasicsNext Topic ⮕
Sets⬅ Previous Topic
Recursion BasicsNext Topic ⮕
SetsAn 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.
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.
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
value = 30 array = [10, 20, 30, 40, 100]
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.
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
10 20 30 40 100
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)
100
sum = 0
for i from 0 to length of array - 1 do
sum = sum + array[i]
end for
print(sum)
200
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).
If you need a dynamic data structure that grows or shrinks, consider using a List or Dynamic Array instead.
⬅ Previous Topic
Recursion BasicsNext Topic ⮕
SetsYou can support this website with a contribution of your choice.
When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.