Array Data Structure

Amit KesarwaniAmit Kesarwani
4 min read

Mastering Arrays in C++: From Basics to 2D Arrays with Real Problems

Introduction

Arrays are the backbone of many data structures and algorithms. They allow you to store a fixed-size sequence of elements of the same type. Understanding arrays, especially in C++, is crucial for any programmer or DSA enthusiast. Let's explore 1D and 2D arrays, their creation, usage, memory structure, and common problems.


What is an Array?

An array is a collection of elements, all of the same type, stored in contiguous memory locations.

Syntax

int a[5]; // creates an integer array of size 5

How to Create and Use Arrays

—>Declaration:

int a[10];  // Array of size 10

—>Assignment:

a[0] = 5;
a[1] = 10;

—> Initialization:

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

If partially initialized:

int a[5] = {1, 2};  // Rest will be filled with 0

  • Assignment vs Initialization

Initialization

Done while declaring the array:

int a[3] = {1, 2, 3};

Assignment

Done after declaration:

int a[3];
a[0] = 1;
a[1] = 2;
a[2] = 3;

When to Use What?

  • Use initialization if values are known in advance.

  • Use assignment if values are computed later.


What is a Garbage Value?

If you declare an array but don’t initialize it, it holds garbage values (random memory content):

int a[5];
cout << a[0]; // garbage value

✅ Garbage values come when:

  • Local arrays are declared without initialization.

Finding Maximum Element in Array

Code:

int maxElement(int a[], int n) {
    int max = a[0];
    for (int i = 1; i < n; i++) {
        if (a[i] > max)
            max = a[i];
    }
    return max;
}

Problem 2: Remove Duplicates from Sorted Array

Leetcode-style Problem:

Remove duplicates in-place and return new length.

Code:

class Solution {
public:
    int removeDuplicates(vector<int>& nums) {
        int n =nums.size();
        int j = 1;

        for(int i=1; i<n; i++){
            if(nums[i] != nums[j-1]){
                nums[j] = nums[i];
                j++;
            }
        }
        return j;
    }
};

Problem 3: Merge Sorted Arrays

Merge nums2[] into nums1[] as one sorted array.

class Solution {
public:
    void merge(vector<int>& nums1, int m, vector<int>& nums2, int n) {
        int i= m-1;
        int j =n-1;
        int k= m+n-1;
        while (i>=0 && j>=0){
            if(nums1[i] > nums2[j]){
                nums1[k] = nums1[i];
                k--;
                i--;
            }
            else{
                nums1[k]=nums2[j];
                k--;
                j--;
            }
        }
        while(j>=0){
            nums1[k] = nums2[j];
            j--;
            k--;
        }

    }
};

Part-2: What is Two Dimensional Array?

—> A 2D array is like an array of arrays — a table or matrix format.

Declaration:

int a[2][3];

Initialization:

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

Why Array Starts at Index 0?

The address of an element is calculated based on its offset from the base address. So:

a[i] = *(a + i); // for 1D

For 2D:

a[i][j] = *(*(a + i) + j);

How Internally Stored?

Stored as a 1D flattened row-wise (in C++):

1 2 3
4 5 6 => 1 2 3 4 5 6

Address Formula:

Address of 2D array
 a[i][j] = Base address + (i * number of columns * size of data type) + (j * size of data type)

Real Life Example:

A building floor plan:

  • Floor = Row

  • Room = Column

  • To reach room[2][3] → go to 3rd floor (index 2), enter 4th room (index 3)


2D Practice Problem: Leetcode 463. Island Perimeter

Problem:

Find perimeter of 1s where land touches water (0).

Code:

class Solution {
public:
    int islandPerimeter(vector<vector<int>>& grid) {
        int perimeter =0;
        int rows = grid.size();
        int cols = grid[0].size();

        for(int i=0; i<rows; ++i){
            for(int j = 0; j<cols; ++j) {
                if(grid[i][j] == 1) {

                    if(i == 0 || grid[i-1] [j] == 0) perimeter++;  //up
                     if(i == rows-1 || grid[i+1] [j]== 0) perimeter++;  //down
                      if(j == 0 || grid[i][j-1] == 0) perimeter++;     //left
                       if(j == cols-1 || grid[i][j+1] == 0) perimeter++;  //right
                }
            }

        }
        return perimeter;

    }
};

Conclusion

Arrays are the most foundational data structure. Understanding their working, memory layout, addressing, and applications will build a strong base for further learning in DSA. With practical examples and problems, you now have a solid grasp of both 1D and 2D arrays.

Stay tuned for Part-3 where we’ll cover pointers and dynamic arrays!

0
Subscribe to my newsletter

Read articles from Amit Kesarwani directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Amit Kesarwani
Amit Kesarwani