👁 Preview — Study, Practice and Revise are open; mock tests and the rest of the syllabus unlock on subscription. Unlock all · ₹4,999
← Back to Programming Fundamentals
Study mode

Arrays and Data Structures

Introduction

Imagine you have a row of lockers, each numbered and used to store similar items like books or files. This simple idea helps us understand arrays, one of the most fundamental data structures in programming. Arrays allow us to store multiple values of the same type in an organized way, making it easier to access, manage, and manipulate data efficiently.

In programming, data structures are essential because they help organize data so that operations like searching, inserting, or deleting can be done quickly and effectively. Without proper data structures, even simple tasks can become complicated and slow, especially when dealing with large amounts of data.

In this section, we will explore arrays and other important data structures, understand how they work, and learn how to perform basic operations on them. This knowledge is crucial for solving problems in competitive exams and real-world programming.

Arrays

An array is a collection of elements, all of the same data type, stored in contiguous memory locations. This means that the elements are placed one after another in memory, like a row of lockers or seats in a theatre.

Arrays have two main characteristics:

  • Fixed size: The number of elements in an array is decided when the array is created and cannot be changed later.
  • Homogeneous data type: All elements in the array must be of the same type, such as all integers, all characters, or all floating-point numbers.

Arrays can be classified based on their dimensions:

  • One-Dimensional (1D) Arrays: A simple list of elements arranged in a single row.
  • Two-Dimensional (2D) Arrays: Elements arranged in rows and columns, like a table or spreadsheet.
  • Multi-Dimensional Arrays: Arrays with three or more dimensions, used in advanced applications like 3D graphics.

Each element in an array is identified by an index, which represents its position. In most programming languages, array indices start at 0. This means the first element is at index 0, the second at index 1, and so on.

10 20 30 40 50 60 70 0 1 2 3 4 5 6

For example, consider an array that stores the marks of 7 students in a test: [10, 20, 30, 40, 50, 60, 70]. The first student's marks are at index 0, the second at index 1, and so on.

Arrays are stored in contiguous memory locations, which means the memory addresses of elements are consecutive. This allows quick access to any element if we know its index.

Array Operations

Arrays support several basic operations that are essential for data manipulation:

  • Traversal: Accessing each element of the array, usually to read or display values.
  • Insertion: Adding a new element at a specific position.
  • Deletion: Removing an element from a specific position.
  • Searching: Finding the position of a specific element.

Let's understand these operations step-by-step.

graph TD    Start[Start] --> Init[Set index i = 0]    Init --> CheckI{i < array size?}    CheckI -- Yes --> Access[Access element at index i]    Access --> Increment[Increment i by 1]    Increment --> CheckI    CheckI -- No --> End[End traversal]    InsertStart[Start Insertion] --> CheckPos{Is position valid?}    CheckPos -- No --> Error[Show error: Invalid position]    CheckPos -- Yes --> Shift[Shift elements from end to position]    Shift --> Insert[Insert new element at position]    Insert --> EndInsert[End insertion]

Traversal involves visiting each element from the first to the last. This is often done using a loop.

Insertion in an array requires shifting elements to the right from the insertion point to make space for the new element. Since arrays have fixed size, insertion is only possible if there is free space.

Deletion is the opposite of insertion: elements after the deleted element are shifted left to fill the gap.

Searching can be done by checking each element one by one (linear search) or by more efficient methods if the array is sorted.

Each of these operations has a time cost, called time complexity, which we will discuss later in the chapter.

Linear Data Structures

Besides arrays, there are other important linear data structures that organize data in a sequence. These include:

  • Linked Lists: A collection of nodes where each node contains data and a reference (or pointer) to the next node.
  • Stacks: Data structures that follow the Last-In-First-Out (LIFO) principle, where the last element added is the first to be removed.
  • Queues: Data structures that follow the First-In-First-Out (FIFO) principle, where the first element added is the first to be removed.

Unlike arrays, linked lists do not store elements in contiguous memory locations. Instead, each element points to the next, allowing dynamic memory usage and easier insertion/deletion.

Array (Contiguous Memory) 10 20 30 40 Linked List (Nodes with Pointers) 10 -> 20 -> 30 NULL

In the diagram above, the array stores elements in adjacent boxes, while the linked list stores data in nodes connected by pointers (arrows). This difference affects how data is accessed and modified.

Key Concept: Why Use Different Data Structures?

Arrays are simple and fast for accessing elements by index, but have fixed size and costly insertions/deletions. Linked lists and other linear structures offer flexibility in size and easier insertions/deletions but require more memory and slower access.

Formula Bank

Index Calculation for 1D Array
\[ \text{Address} = \text{BaseAddress} + (\text{Index} \times \text{SizeOfElement}) \]
where: BaseAddress = starting memory address of array, Index = position of element (0-based), SizeOfElement = size of each element in bytes
Index Calculation for 2D Array (Row Major)
\[ \text{Address} = \text{BaseAddress} + ((\text{Row} \times \text{NumberOfColumns}) + \text{Column}) \times \text{SizeOfElement} \]
where: BaseAddress = starting memory address, Row = row index (0-based), Column = column index (0-based), NumberOfColumns = total columns, SizeOfElement = size of each element

Worked Examples

Example 1: Traversing a One-Dimensional Array Easy
Given an array of integers: [5, 10, 15, 20, 25], write steps to print all elements.

Step 1: Start with the first element at index 0.

Step 2: Access the element at the current index and print it.

Step 3: Move to the next index by incrementing the index by 1.

Step 4: Repeat steps 2 and 3 until the last element (index 4) is printed.

Answer: The elements printed are 5, 10, 15, 20, 25 in order.

Example 2: Inserting an Element in an Array Medium
Insert the element 35 at index 3 in the array [10, 20, 30, 40, 50]. Assume there is space for one more element.

Step 1: Identify the insertion position (index 3).

Step 2: Shift elements from the last index (4) to index 3 one position to the right to make space.

Step 3: Place the new element 35 at index 3.

Step 4: The updated array is [10, 20, 30, 35, 40, 50].

graph TD    Start[Start] --> CheckPos{Is index valid?}    CheckPos -- No --> Error[Show error: Invalid index]    CheckPos -- Yes --> Shift[Shift elements from end to index right by one]    Shift --> Insert[Insert new element at index]    Insert --> End[End]
Example 3: Searching for an Element Using Linear Search Easy
Find the index of element 40 in the array [10, 20, 30, 40, 50] using linear search.

Step 1: Start at index 0, check if element is 40.

Step 2: If not, move to next index and repeat.

Step 3: At index 3, element is 40, so stop search.

Answer: Element 40 found at index 3.

Example 4: Implementing a Stack Using Arrays Medium
Implement push and pop operations on a stack using an array of size 5. Show what happens when pushing elements 10, 20, 30 and then popping one element.

Step 1: Initialize an empty stack with a top pointer set to -1.

Step 2: Push 10: increment top to 0, store 10 at index 0.

Step 3: Push 20: increment top to 1, store 20 at index 1.

Step 4: Push 30: increment top to 2, store 30 at index 2.

Step 5: Pop: remove element at top index 2 (30), decrement top to 1.

Answer: Stack after operations: [10, 20], top at index 1.

10 20 30 Top
Example 5: Comparing Time Complexity of Array Operations Hard
Analyze the time complexity (best, average, worst cases) of searching, insertion, and deletion in arrays.

Searching:

  • Best case: \(O(1)\) if element is at first index.
  • Average and worst case: \(O(n)\) where n is number of elements (linear search).

Insertion:

  • Best case: \(O(1)\) if inserting at the end (if space available).
  • Average and worst case: \(O(n)\) if inserting at beginning or middle (due to shifting elements).

Deletion:

  • Best case: \(O(1)\) if deleting last element.
  • Average and worst case: \(O(n)\) if deleting from beginning or middle (due to shifting elements).
Time Complexity of Array Operations
Operation Best Case Average Case Worst Case
Searching O(1) O(n) O(n)
Insertion O(1) O(n) O(n)
Deletion O(1) O(n) O(n)

Summary

Arrays provide fast access by index but can be slow for insertions and deletions except at the end. Understanding time complexity helps in choosing the right data structure for a problem.

Tips & Tricks

Tip: Remember array indices start at 0

When to use: While accessing or iterating over arrays to avoid off-by-one errors

Tip: Use binary search only on sorted arrays

When to use: When searching efficiently in large datasets

Tip: For insertion in arrays, shift elements from the end to the insertion point

When to use: To correctly insert elements without overwriting data

Tip: Visualize data structures with diagrams to understand memory layout

When to use: When learning new data structures or debugging code

Tip: Practice writing pseudocode before coding

When to use: To clarify logic and reduce syntax errors during exams

Common Mistakes to Avoid

❌ Confusing array size with last index
✓ Remember last index is size - 1
Why: Because array indexing starts at 0, leading to off-by-one errors
❌ Attempting to insert elements beyond array size without resizing
✓ Check array bounds before insertion or use dynamic structures
Why: Fixed-size arrays cannot expand, causing runtime errors
❌ Using binary search on unsorted arrays
✓ Sort the array first or use linear search
Why: Binary search requires sorted data to function correctly
❌ Ignoring underflow and overflow conditions in stack implementations
✓ Always check before push or pop operations
Why: To prevent runtime errors and data corruption
❌ Misunderstanding row-major vs column-major order in 2D arrays
✓ Learn and apply correct formula for address calculation
Why: Incorrect indexing leads to accessing wrong memory locations
✨ AI exam tools — try them free (included in every plan)
Tip: select any text above to Explain / Example / Simplify it.
Curated videos per subtopic
Top YouTube explainers, AI-ranked for your exam and language. Unlocks with subscription.
Unlock

Try Practice next.

Progress tracking is paywalled — subscribe to mark subtopics as understood and save your streak.

Go to practice →
Ask a doubt
Arrays and Data Structures · 10 free messages
Ask me anything about this subtopic. You have 10 free messages this session — chat history isn't saved in preview.