Table of contents
1.
Introduction
2.
What is an Array?
3.
Why do we need an array?
4.
Indexing in the Array
5.
Syntax of an array declaration
6.
Initialization Methods in an Array:
6.1.
Static Initialization
6.2.
Dynamic Initialization
6.3.
Zero Initialization
6.4.
Initialization with Default Values
7.
Types of array declaration in C++
7.1.
Declaration of an array by specifying the size
7.1.1.
Implementation
7.2.
Declaration of an array by initializing elements
7.2.1.
Implementation
7.3.
Declaration of an array by specifying the size and initializing elements
7.3.1.
Implementation
8.
Accessing Array Elements in C++
8.1.
Using Index to Access Elements
8.2.
Looping Through Arrays
9.
Types of Arrays in C++
9.1.
One-Dimensional Arrays
9.2.
Multi-Dimensional Arrays
9.3.
Jagged Arrays
10.
Common Array Operations in C++
10.1.
Sorting Arrays
10.2.
Searching for Elements
10.3.
Reversing Arrays
11.
Best Practices for Working with Arrays
11.1.
Memory Management in Arrays
11.2.
Handling Array Bounds
12.
When to Use Arrays in C++
12.1.
Real-World Examples of Array Usage
13.
Advantages of an Array
14.
Disadvantages of an Array
15.
Frequently asked questions
15.1.
How to Write an Array in C++?
15.2.
How Many Data Types Are in an Array?
15.3.
What is the Length of an Array?
16.
Conclusion
Last Updated: May 2, 2025
Easy

Introduction to Array

Author Shivam Verma
1 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

An array is one of the most fundamental data structures in programming, providing a way to store multiple values of the same type in a single, contiguous block of memory. Arrays are widely used across various programming languages due to their simplicity and efficiency in managing and accessing collections of data. 

Introduction to Array

Whether you’re dealing with a list of numbers, a series of characters, or any other set of elements, arrays offer a straightforward method to organize and manipulate this data. In this blog, we will explore the concept of arrays, their syntax, and how they can be utilized to solve common programming problems. Understanding arrays is a key step in mastering more complex data structures and algorithms, making them an essential topic for any aspiring programmer.

example of array

Also see, Literals in C.Fibonacci Series in C++

What is an Array?

An array is a data structure that allows you to store multiple elements of the same data type in a single, contiguous block of memory. Each element in an array is identified by an index, which indicates its position within the array. The index typically starts at 0, meaning the first element is at index 0, the second at index 1, and so on.

Arrays provide a convenient way to manage and manipulate large sets of related data. Instead of creating individual variables for each value, you can use an array to group them together, making your code more organized and easier to manage. For example, if you need to store the grades of 100 students, instead of creating 100 separate variables, you can create an array with 100 elements.

Why do we need an array?

Arrays are a very useful data structure in any programming language. Using an Array, we can store the values of more than one variable of the same data type together instead of storing these values separately. We can access every value of the array individually. For example, if you want to store more than one integer type of data, you can store them separately by taking integer type variables. But it is not an excellent method to store these values. We can store these values easily by using an array.

Indexing in the Array

Indexing in an array refers to the method of accessing elements based on their position within the array. Each element in an array is assigned a unique index, which allows you to retrieve or modify the element efficiently. The index is a numerical value that represents the position of an element within the array, with indexing typically starting from 0.

There are several key points about Indexing:

1. Zero-Based Indexing:

  • In most programming languages, arrays use zero-based indexing. This means that the first element of the array is accessed with index 0, the second element with index 1, and so on. For example, in an array named arr, arr[0] refers to the first element, arr[1] refers to the second element, and so forth.

2. Positive and Negative Indexing:

  • In some languages, you can use negative indexing to access elements from the end of the array. For instance, arr[-1] typically refers to the last element, arr[-2] refers to the second-to-last element, and so on. This feature is common in languages like Python.

3. Out-of-Bounds Access:

  • Accessing an element using an index that is outside the valid range (i.e., less than 0 or greater than or equal to the array size) results in an error or undefined behavior. This is known as an out-of-bounds access and can lead to runtime errors or program crashes.

4. Indexing Examples:

  • Consider an array arr of size 5: int arr[5] = {10, 20, 30, 40, 50};
    • arr[0] will access the value 10
    • arr[1] will access the value 20
    • arr[4] will access the value 50
  • If you attempt to access arr[5] or arr[-1] in a zero-based indexing language, it would typically result in an error.

Syntax of an array declaration

type array_name[array_size]; 

In the above syntax, type means the data type and array_name is the name of the array you want to create, and array_size is the number of the element you want to store in the array.

For example

int marks[6];

Here int is a data type, and the 'marks' is the array's name, and 6 is the size of the array.

Initialization Methods in an Array:

Initializing an array involves assigning values to its elements when it is created. Different programming languages offer various methods for initializing arrays, allowing you to set up your data structure in a way that suits your needs. Here are some common initialization methods:

Static Initialization

1. Direct Initialization: You can initialize an array with a set of values at the time of declaration. This method is straightforward and is used when you know the values you want to assign in advance.

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

In this example, arr is an integer array with 5 elements, initialized with the values 10, 20, 30, 40, and 50.

2. Partial Initialization: If you provide fewer values than the size of the array, the remaining elements are automatically initialized to zero (for numeric types) or null (for pointers). 

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

Dynamic Initialization

1. Using a Loop: You can initialize an array dynamically by using loops, which is useful when the values are determined during runtime or are generated algorithmically.

int arr[5]; 
for (int i = 0; i < 5; i++) 
{ 
arr[i] = i * 10; 
}

Here, each element of the array arr is initialized to a value based on its index.

2. Function-Based Initialization: Some programming languages provide functions or methods to initialize arrays. For example, in Python, you can use list comprehensions or functions to create and initialize arrays. 

arr = [i * 10 for i in range(5)]

Zero Initialization

In many languages, you can explicitly initialize an array with zero values. This is particularly useful for numeric arrays where you want to start with a known base state. 

int arr[5] = {0};

Initialization with Default Values

Some languages allow you to initialize arrays with default values. For example, in C++, you can use the std::fill function from the Standard Library to set all elements to a specific value.

#include <algorithm>
int arr[5];
std::fill(std::begin(arr), std::end(arr), 42); // All elements are set to 42

Types of array declaration in C++

  • Declaration of an array by specifying the size
  • Declaration of an array by initialising elements
  • Declaration of an array by specifying the size and initialising elements

Declaration of an array by specifying the size

Implementation

// declaration of an array by specifying size
int arr1[5];
// another way of declaration of an array by specifying size
int n=5;
int arr2[n];

In the above code, the compiler creates an array of size 5. The elements of the array are not initialized. 

Declaration of an array by initializing elements

Implementation

// declaration of an array by initializing elements
int arr[] = {15, 25, 35, 45, 55}

In the above code, the compiler creates an array of size 5. The Elements of the array are {15, 25, 35, 45, 55}.

Declaration of an array by specifying the size and initializing elements

Implementation

// Declaration of an array by specifying size and initializing elements
// elements
int arr[7] = { 15, 26, 28, 60,45 }

In the above code, the compiler creates an array of size seven and then initializes the first five elements as specified by the user and the rest two elements as 0.

Accessing Array Elements in C++

Using Index to Access Elements

In C++, arrays are collections of elements stored in a fixed-size sequence. Each element in the array can be accessed using an index. An index is a number that tells the position of an element in the array. In C++, array indices start from 0. This means the first element is at index 0, the second at index 1, and so on.

Here’s a simple example of accessing array elements using an index:

#include <iostream>
using namespace std;

int main() {
    int numbers[5] = {10, 20, 30, 40, 50};
    cout << "The first element is: " << numbers[0] << endl;
    cout << "The third element is: " << numbers[2] << endl;
    return 0;
}
You can also try this code with Online C++ Compiler
Run Code

In this code, numbers[0] gives the first element 10, and numbers[2] gives the third element 30.

Accessing an element outside the valid range of the array (for example, numbers[5] in the example above) can cause undefined behavior. The program may crash or return garbage values. Always make sure the index is within the array's size to avoid such errors.

Indexing is a simple and fast way to work with arrays, but always remember to keep it safe.

Looping Through Arrays

When working with arrays in C++, especially large ones, it's common to use loops to access each element. This avoids writing repetitive code for every index.

The most common way is using a for loop, like this:

#include <iostream>
using namespace std;

int main() {
    int scores[5] = {90, 80, 70, 60, 50};
    for (int i = 0; i < 5; i++) {
        cout << "Element at index " << i << ": " << scores[i] << endl;
    }
    return 0;
}
You can also try this code with Online C++ Compiler
Run Code

This loop starts from i = 0 and goes up to i = 4, accessing each element using scores[i]. This is useful when you need the index for calculations or position-based logic.

From C++11 onward, you can also use a range-based for loop. This loop goes through each element directly, without using an index:

#include <iostream>
using namespace std;

int main() {
    int marks[4] = {85, 90, 95, 100};
    for (int mark : marks) {
        cout << "Mark: " << mark << endl;
    }
    return 0;
}
You can also try this code with Online C++ Compiler
Run Code

This method is cleaner and easier to read, especially when you don't need to know the index. However, if you need to modify the values or work with their positions, a traditional for loop is better.

Use range-based loops when you only need to read values, and use regular for loops when you need index control or want to change values.

Looping makes it easy to work with every element in the array, and knowing when to use each loop style helps you write better C++ code.

Types of Arrays in C++

One-Dimensional Arrays

A one-dimensional array in C++ is a list of elements of the same data type stored in a continuous block of memory. It is the simplest form of an array. You can think of it as a row of boxes, where each box holds a value.

To declare a one-dimensional array, you specify the type, array name, and size. For example:

int numbers[5] = {10, 20, 30, 40, 50};

In this example, we declared an integer array named numbers with five elements. You can access each element using an index, starting from 0:

cout << numbers[0]; // prints 10
cout << numbers[1]; // prints 20


Arrays help store multiple values under one variable name, which is useful when working with a fixed number of items like scores, marks, or ages. One-dimensional arrays are easy to loop through using a for loop.

for (int i = 0; i < 5; i++) {
    cout << numbers[i] << " ";
}

Multi-Dimensional Arrays

Multi-dimensional arrays are arrays that contain more than one index or dimension. The most common type is the two-dimensional array, which you can imagine as a table with rows and columns.

In C++, a two-dimensional array is declared like this:

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


Here, matrix has 2 rows and 3 columns. You can access elements using two indices:

cout << matrix[0][1]; // prints 2


Two-dimensional arrays are useful when dealing with grid-based data, like game boards or mathematical matrices.

You can loop through a 2D array using nested loops:

for (int i = 0; i < 2; i++) {
    for (int j = 0; j < 3; j++) {
        cout << matrix[i][j] << " ";
    }
    cout << endl;
}


Multi-dimensional arrays provide a clean way to manage data in rows and columns. They are often used in matrix operations, image processing, and data tables.

Jagged Arrays

C++ does not support jagged arrays (arrays of arrays with different lengths) in the same way languages like C# or Java do. But you can achieve the same using pointers and dynamic memory.

A jagged array is useful when you need to store rows of different lengths. For example:

int* jagged[3];
jagged[0] = new int[2];
jagged[1] = new int[4];
jagged[2] = new int[3];

Here, each row has a different number of elements. This setup is helpful when you don't know the size of each row in advance.

You can assign and access values like this:

jagged[0][0] = 1;
jagged[0][1] = 2;
cout << jagged[0][1]; // prints 2

Use jagged arrays when your data has varying lengths per row, like storing exam scores for students who took a different number of subjects.

Common Array Operations in C++

Sorting Arrays

Sorting means arranging elements in a specific order, either ascending or descending. Sorting helps when you need to search quickly or analyze data.

Common sorting algorithms in C++ include:

  • Bubble Sort
     
  • Selection Sort
     
  • Quick Sort

However, for quick and easy sorting, you can use std::sort() from the C++ Standard Library:

#include <algorithm>
int arr[] = {5, 2, 8, 1, 9};
std::sort(arr, arr + 5); // sorts in ascending order

To sort in descending order:

std::sort(arr, arr + 5, greater<int>());

Here's a simple bubble sort example:

for (int i = 0; i < 5 - 1; i++) {
    for (int j = 0; j < 5 - i - 1; j++) {
        if (arr[j] > arr[j + 1]) {
            swap(arr[j], arr[j + 1]);
        }
    }
}


Sorting helps organize data and is commonly used in statistics, ranking, and optimization problems.

Searching for Elements

Searching lets you find if an element exists in an array and where it is located.

Linear Search checks each element one by one:

int search = 10;
bool found = false;
for (int i = 0; i < 5; i++) {
    if (arr[i] == search) {
        found = true;
        break;
    }
}

Binary Search works on sorted arrays and is faster:

#include <algorithm>
bool exists = binary_search(arr, arr + 5, 10);


Linear search is easy but slow for large arrays. Binary search is faster but requires sorted data.

Reversing Arrays

Reversing an array means swapping the first element with the last, the second with the second-last, and so on.

To reverse manually:

for (int i = 0; i < n / 2; i++) {
    swap(arr[i], arr[n - i - 1]);
}


Or use the built-in function:

#include <algorithm>
std::reverse(arr, arr + n);


Reversing is useful in cases like undo operations, palindrome checks, or formatting data backward.

Best Practices for Working with Arrays

Memory Management in Arrays

In C++, memory for arrays can be allocated statically or dynamically.

Static arrays are declared with a fixed size:

int arr[10];


Dynamic arrays allow runtime allocation using new:

int* arr = new int[10];


When using dynamic arrays, you must free memory to avoid leaks:

delete[] arr;


Static arrays are simple and safe when you know the size. Dynamic arrays are useful when size is unknown at compile time.

Improper memory management can lead to memory leaks and crashes, especially in long-running applications.

Handling Array Bounds

C++ does not check if you're accessing a valid index. Accessing outside the array bounds leads to undefined behavior.

For example:

int arr[5];
arr[10] = 25; // dangerous!

To avoid errors:

  • Use loops that respect array size.
     
  • Use constants or variables to define sizes.
     
  • Always check index validity before accessing.
     
  • Safe code prevents bugs and crashes.

When to Use Arrays in C++

Real-World Examples of Array Usage

Arrays are perfect for storing fixed-size data. They are fast and use less memory compared to advanced containers.

Examples:

  • Storing marks of 5 students: int marks[5];
     
  • Representing a 3x3 game grid: char board[3][3];
     
  • Holding sensor readings: float readings[10];
     
  • Arrays work well in real-time systems, embedded devices, and simple programs. Use them when you know the data size in advance.
     

However, arrays are not ideal for situations where size changes frequently. In such cases, use std::vector or other STL containers.

Arrays are best used when performance and simplicity matter.

Advantages of an Array

  • An array can store various data items of the same data type using a single name.
  • Traversal of the array becomes easy using a single loop.
  • You can randomly access an element in an array by using the index number.
  • Sorting of the element is very easy in an array.
  • Array allocates memory in the contiguous memory location, so there is no wastage of memory in the array.

Disadvantages of an Array

  • The number of elements you want to store in an array should be known in advance.
  • Insertion and deletion in the array are very difficult because the elements in the array are stored in consecutive order.
  • An array is a static data structure so that you can not increase the size once the array is declared.
  • Allocating more memory than the requirement leads to the wastage of memory, and less allocation of memory also leads to a problem.  

Frequently asked questions

How to Write an Array in C++?

Declare an array with its type and size, then optionally initialize it. Example:

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

How Many Data Types Are in an Array?

An array in C++ can only contain elements of a single data type. Mixing types in one array is not allowed.

What is the Length of an Array?

The length of a statically allocated array can be determined using:

int length = sizeof(arr) / sizeof(arr[0]);

Conclusion

In this blog, we have discussed about arrays. Arrays are a fundamental data structure that simplify the management and organization of multiple elements of the same type. Understanding arrays is crucial for efficient data handling in programming, enabling straightforward access, manipulation, and storage of data. 

Live masterclass