1
AN ARRAY
An array is a collection of items stored at similar(contiguous) memory locations. It allows you
to store multiple values of the same type in a single data structure, making it easier to manage
and manipulate data.
An array is a special variable, which can hold more than one value:
Here’s a breakdown to help you understand arrays:
1. Characteristics of an Array:
Fixed Size: The size of the array is defined at creation and cannot be changed.
Indexed Access: Each element in the array is associated with an index, starting from 0.
Homogeneous Data: All elements in the array must be of the same data type (e.g.,
integers, strings, etc.).
2. How Arrays Work:
Imagine a row of boxes, each box storing a value:
Array: [10, 20, 30, 40]
Index: 0 1 2 3
To access or modify elements, you use the index:
Accessing: array[1] gives 20.
Modifying: array[2] = 50 changes the array to [10, 20, 50, 40].
3. Real-World Example:
Think of an array as a bookshelf where:
Each shelf is a slot (index) in the array.
You can store one book (value) in each slot.
4. Basic Operations:
OLWANDE ERICK +254729207653 1
2
- Declaration (Creating an Array):
In different languages, the syntax varies:
Python:
numbers = [10, 20, 30, 40] # List used as an array
Java:
int[] numbers = {10, 20, 30, 40};
C++:
int numbers[] = {10, 20, 30, 40};
- Accessing Elements:
print(numbers[1]) # Output: 20
- Updating Elements:
numbers[2] = 50 # Array becomes [10, 20, 50, 40]
5. Advantages of Arrays:
Efficient access: Fast random access using an index.
Easy data management: You can group related values together.
6. Limitations of Arrays:
Fixed size: You can’t add or remove elements dynamically (use other structures like lists
in Python or Array Lists in Java for flexibility).
Homogeneous data: All elements must be of the same type.
7. Example Use Cases:
Storing grades of students.
Tracking the inventory of items in a shop.
Managing frames in a game.
OLWANDE ERICK +254729207653 2