Arrays in Data Structures

What Is an Array?

An Array is a simple data structure that stores multiple values in continuous memory locations.
You can think of an array like a row of lockers – each locker has an index, and you can store one value in each.

Example in real life: A row of seats in a classroom – each seat has a fixed position.

Why Do We Use Arrays?

Arrays are used because they are:

  • Easy to understand
  • Fast to access any element
  • Perfect for storing a collection of similar items
  • Used in almost every programming language

If you know arrays well, other data structures become easier to learn.

How Arrays Work (Simple Explanation)

  • Every element in an array has a fixed position called an index.
  • Indexing starts from 0.
  • All elements are stored side by side in memory.

Example:

Index:   0   1   2   3   4
Value:  10  20  30  40  50

Key Features of Arrays

  • Fixed size: Once created, you cannot change the size.
  • Fast access: Accessing any element is very fast — O(1).
  • Same data type: All elements must be of the same type (int, float, string, etc.).
  • Continuous memory: Stored in consecutive locations.

Types of Arrays

Arrays are mainly of two types:

1. One-Dimensional Array

A simple list of values.

Example:

int[] arr = {10, 20, 30};

2. Multi-Dimensional Array

Arrays inside arrays.

Example (2D Array):

int[][] matrix = {
{1, 2, 3},
{4, 5, 6}
};

Advantages of Arrays

  • Fast access using index (O(1))
  • Easy to iterate and manage
  • Best structure for fixed-size data
  • Very memory efficient

Disadvantages of Arrays

  • Fixed size — cannot grow or shrink
  • Inserting/deleting in the middle is slow
  • Wastes memory if array is too large