Introduction to Arrays

Introduction to Arrays in C++ Language

On this page, we will discuss the introduction to arrays in C++, a fundamental concept that every beginner should understand. Arrays are a type of data structure that allow us to store multiple values of the same data type in a single, organized collection. These values are stored in contiguous memory locations, making access and manipulation efficient.

introduction to arrays in c++

Introduction To Arrays In C++ Programming

An array is a data structure that stores a collection of elements of the same data type, arranged in a contiguous block of memory. Each element in the array can be accessed using an index, which represents its position in the array.

Arrays are commonly used in programming because they allow us to store and manipulate large amounts of data efficiently. They also enable us to perform operations on multiple elements of the array at once, using loops or other control structures.

Arrays can be declared with a fixed size, which is determined at the time of creation, or they can be dynamic, which means that their size can be adjusted during runtime. In many programming languages, arrays are zero-indexed, which means that the first element is stored at index 0.

Introduction to Arrays in C++

Why should we use array in Programming

  1. Efficient storage: Arrays allow you to store large amounts of data efficiently in a contiguous block of memory. This means that you can access and manipulate the data quickly and efficiently.

  2. Random access: Arrays provide random access to individual elements, which means that you can access any element in the array directly by its index. This makes it easy to access and modify specific elements of the data set.

  3. Iteration: Arrays allow you to iterate over all the elements in the array using a loop or other control structure. This makes it easy to perform operations on all the elements in the array at once.

  4. Multi-dimensional: Arrays can be multidimensional, meaning that they can have multiple rows and columns of data. This makes them useful for storing and manipulating complex data sets, such as matrices or tables.

  5. Ease of use: Many programming languages provide built-in support for arrays, making them easy to use and integrate into your programs.

Declaration of Arrays in C++ Programming Language

 Declaration of Array can be done by the following way in C Languge:
    Syntax : Data_type  array_name  [Array_size] ; 
Example : integer Array : int student [50]; char Array : char student [50]; (Character Array is also known as String in C Programming Language) float Array : float student [50]; double Array : double student [50];

Initialization of Arrays in C++ Programming Language

 Array can be initialized in C++ programming language in the compile time or in the run time.

Initialization of Array in Run Time

Initialization of Array at Run Time means declaring the elements of array after running the code. Here, elements are taken from user.
we can also set the the size of array when we initialize array at run time.

Run
#include <iostream>

using namespace std;

int main()
{
    int n;                          //size of array
    cin>>n;
    int student[n];                 //array
    for(int i=0; i<n; i++) cin>>student[i];
    return 0;
}

Initialization of Array in Compile Time

Initialization of Array at compile means declaring the elements of array before running the code at the time of declaration which can be done as follow:

Run
#include <iostream>

using namespace std;

int main()
{
    //integer array
    int student1[5] = {60, 70, 65, 80, 85};
    //float array
    float student2[5] = {60.0, 75.5, 80.0, 67.0, 83.5};
    return 0;
}

C++ Code Accessing the elements of Arrays

Run
#include <iostream>

using namespace std;

int
main ()
{
  // Declare an array of integers
  int arr[] = { 1, 2, 3, 4, 5 };

  // Calculate the length of the array
  int arrLen = sizeof (arr) / sizeof (int);

  // Access all the elements of the array using a loop
  for (int i = 0; i < arrLen; i++)
    {
      cout << "Element " << i << " = " << arr[i] << endl;
    }

  return 0;
}

Output

Element 0 = 1
Element 1 = 2
Element 2 = 3
Element 3 = 4
Element 4 = 5
Introduction to Arrays in C

Proving Array follows Contagious Memory Allocation

 The program given below proves that the Array follows contagious memory allocation

Run
#include <iostream>

using namespace std;

int main ()
{
  // Declare an array of integers
  int arr[] = { 1, 2, 3, 4, 5 };

  // Print the memory address of the first element
  cout << "Address of first element: " << &arr[0] << endl;

  // Print the memory address of the second element
  cout << "Address of second element: " << &arr[1] << endl;

  // Print the memory address of the third element
  cout << "Address of third element: " << &arr[2] << endl;

  return 0;
}

Output

Address of first element: 0x7ffe81b40310
Address of second element: 0x7ffe81b40314
Address of third element: 0x7ffe81b40318

Using Loops to Traverse & Access Elements of Array in C++

  • Arrays store a fixed number of elements of the same data type in contiguous memory.
  • Loops allow us to visit (traverse) each element of the array efficiently.
  • We commonly use for, while, or range-based for loops for traversal.
  • Elements are accessed using their index, starting from 0 up to size – 1.

Example:

Run
#include<iostream>
using namespace std;

int main() {
    int numbers[] = {5, 10, 15, 20, 25};
    int size = sizeof(numbers) / sizeof(numbers[0]);
    int sum = 0;

    for (int i = 0; i < size; i++) {
        sum += numbers[i];
    }

    cout << "Sum of array elements = " << sum;
    return 0;
}

Output

Sum of array elements = 75

Explanation of the Example

  • The array numbers contains 5 integer values.
  • size calculates the total number of elements using sizeof.
  • A for loop runs from 0 to 4 (total 5 iterations).
  • On each iteration, numbers[i] accesses the current element.
  • sum += numbers[i]; adds the current element to the total.
  • Finally, the total sum (75) is printed.

Key Features of Arrays in C++

How To Update/Change Elements In An Array In C++

  • Access the element using its index.
  • Assign a new value to that index using the = operator.
  • You can update multiple elements using loops.
  • Always ensure the index is within the valid range.
  • Arrays have a fixed size; values can change, but size can’t.

Code:

Run
#include 
using namespace std;

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

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

    // Updating array elements
    numbers[0] = 100;  // Change first element
    numbers[2] = 300;  // Change third element

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

    return 0;
}

Output

Original array: 10 20 30 40 50 
Updated array: 100 20 300 40 50

Insert and Print Elements in a C++ Array

  • Declare an array with a fixed size to hold elements.
  • Insert elements by assigning values to specific array indices.
  • Use a loop to print all elements stored in the array.
  • Arrays have a fixed size, so you cannot dynamically add elements beyond the declared size.
  • Access array elements using zero-based indexing (first element is at index 0).

Example:

Run
#include 
using namespace std;

int main() {
    int arr[5]; // Declare an integer array of size 5

    // Insert elements into the array
    arr[0] = 10;
    arr[1] = 20;
    arr[2] = 30;
    arr[3] = 40;
    arr[4] = 50;

    // Print elements of the array
    cout << "Array elements are: ";
    for (int i = 0; i < 5; i++) {
        cout << arr[i] << " ";
    }

    return 0;
}

Output

Array elements are: 10 20 30 40 50 

Explanation:

  • int arr[5]; — Declares an integer array arr that can hold 5 elements.
  • arr[0] = 10; to arr[4] = 50; — Assign values to each position in the array using their indices.
  • The for loop for (int i = 0; i < 5; i++) iterates from index 0 to 4.
  • Inside the loop, cout << arr[i] << ” “; prints each element followed by a space.
  • The program prints all elements in the order they were inserted.

Understanding Arrays with Empty Members in C++

  • In C++, arrays have a fixed size, and all elements exist in memory once declared.
  • If you do not explicitly initialize all elements, the values of uninitialized elements are undefined (can contain garbage values).
  • You can partially initialize an array, and the rest of the elements will be zero-initialized only if you provide partial initialization with braces {}.
  • “Empty” members in arrays do not really exist — every slot holds some value; if not initialized, it’s garbage or zero depending on how the array is declared.
  • It is good practice to initialize all elements or use modern containers like std::vector that handle empty or dynamic elements better.

Example:

Run
#include 
using namespace std;

int main() {
    int arr[5] = {10, 20}; // Partially initialized array

    cout << "Array elements are: ";
    for (int i = 0; i < 5; i++) {
        cout << arr[i] << " ";
    }

    return 0;
}

Output:

Array elements are: 10 20 0 0 0 

Explanation:

  • int arr[5] = {10, 20}; initializes the first two elements with 10 and 20.
  • The remaining 3 elements are automatically initialized to 0 because of partial initialization.
  • The for loop prints all 5 elements of the array.
  • Since uninitialized elements are zero, output shows 0 for those positions.
  • This behavior only applies for static or global arrays or arrays explicitly initialized; otherwise, uninitialized local arrays contain garbage.

Understanding Array Size in C++

  • Arrays have a fixed size declared at compile time (e.g., int arr[5]; means 5 elements).
  • You can calculate the number of elements using sizeof(arr) / sizeof(arr[0]).
  • The array elements are indexed from 0 to size-1.
  • Accessing elements outside this range causes undefined behavior and should be avoided.

Example:

Run
#include 
using namespace std;

int main() {
    int arr[5] = {1, 2, 3, 4, 5};

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

    cout << "Array elements: ";
    for (int i = 0; i < size; i++) {
        cout << arr[i] << " ";
    }
    cout << "\nArray size (number of elements): " << size << endl;

    return 0;
}

Output:

Array elements: 1 2 3 4 5 
Array size (number of elements): 5

Explanation:

  • Declare and initialize an array arr of 5 integers.
  • Compute number of elements using sizeof(arr) / sizeof(arr[0]).
  • Use a loop to print all elements safely using the calculated size.
  • Print the total number of elements after printing array contents.

Passing an Array to a Function in C++

  • Arrays can be passed to functions in two common ways:
    • Method 1: As a standard array parameter (void func(int arr[], int size))
    • Method 2: As a pointer to the array (void func(int* arr, int size))
  • In both methods, you are actually passing a pointer to the first element, not the full array.
  • The size of the array must be passed separately, because C++ does not automatically detect it inside the function.
  • Any changes made to array elements inside the function will affect the original array in the caller function.

Example: Method 1- Pass Array As Function Parameter

Run
#include 
using namespace std;

void printArray(int arr[], int size) {
    cout << "Method 1 - Array elements: ";
    for (int i = 0; i < size; i++) {
        cout << arr[i] << " ";
    }
    cout << endl;
}

int main() {
    int numbers[5] = {10, 20, 30, 40, 50};
    printArray(numbers, 5);
    return 0;
}

Method 2: Pass Array As a Pointer

Run
#include 
using namespace std;

void printArrayPointer(int* arr, int size) {
    cout << "Method 2 - Array elements: ";
    for (int i = 0; i < size; i++) {
        cout << *(arr + i) << " ";
    }
    cout << endl;
}

int main() {
    int numbers[5] = {10, 20, 30, 40, 50};
    printArrayPointer(numbers, 5);
    return 0;
}

Output:

Method 1 - Array elements: 10 20 30 40 50 
Method 2 - Array elements: 10 20 30 40 50

Explanation:

  • Method 1 uses int arr[] in the function parameter, which is interpreted as a pointer to the array’s first element.
  • Method 2 uses int* arr, a direct pointer approach; both behave the same under the hood.
  • In both cases, the function prints array elements using a loop and the size passed.
  • Using *(arr + i) in Method 2 shows how pointer arithmetic can access elements like arr[i].

Types of Arrays in C++

C++ provides several ways to store and access collections of elements using arrays. Depending on the number of dimensions and how data is accessed or stored, arrays can be categorized into the following types:

1. Single Dimensional Array

A single dimensional array is the simplest form of an array, storing elements in a linear sequence.

Syntax Example:

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

Key Points:

  • Elements are accessed using a single index: arr[i]
  • Suitable for storing lists like marks, salaries, or scores.

2. Two-Dimensional Array

A two-dimensional array represents data in rows and columns  similar to a table or matrix.

Syntax Example:

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

Key Points:

  • Elements are accessed using two indices: arr[row][column]
  • Commonly used in matrix operations and grid-based problems.

3. Multidimensional Array

Multidimensional arrays extend beyond two dimensions, allowing representation of more complex data structures.

Syntax Example:

int arr[2][3][4]; // 3D array

Key Points:

  • Elements are accessed with multiple indices: arr[x][y][z]
  • Used in scientific computing, 3D simulations, etc.

4. Pseudo-Multidimensional Array

A pseudo-multidimensional array simulates multi-dimensional behavior using a one-dimensional array. Indexing is manually calculated.

Syntax Example:

int rows = 3, cols = 4;
int arr[12]; // 3 * 4

// To access element at (i, j):
arr[i * cols + j] = 10;

Key Points:

  • More memory-efficient than actual multidimensional arrays.
  • Used when dimensions are dynamic or to optimize performance.

Pointers And Array In C++

In C++, pointers are special variables that store the memory address of another variable. When it comes to arrays, pointers can also be used to access and work with array elements.

Example:

int *ptr;
int arr[5];

// Assign the address of the first array element to the pointer
ptr = arr;

In this example:

  • arr is an array of integers.
  • ptr is a pointer to an integer.
  • The line ptr = arr; assigns the address of the first element of the array (arr[0]) to the pointer ptr.

Now here’s an important point:

In C++, the name of an array (like arr) automatically represents the address of its first element, so writing ptr = arr; is the same as writing:

ptr = &arr[0];

So both lines mean the same thing — they store the address of the first element in the pointer ptr.

You can also access the addresses of other elements like this:

&arr[1], &arr[2], &arr[3], &arr[4]

These give the addresses of the second, third, fourth, and fifth elements of the array.

Key Takeaway:

  • An array name in C++ can be treated like a pointer to its first element.
  • You can use pointers to loop through or manipulate array elements.
  • This relationship makes pointers and arrays closely connected in C++ programming.

Advantages & Disadvantages Of An Array In C++

Advantages of Arrays in C++Disadvantages of Arrays in C++
Easy to access elements using indicesFixed size – cannot grow dynamically
Efficient memory access due to contiguous memory layoutInsertion/deletion is costly (requires shifting elements)
Simple and easy to use for storing multiple valuesWastage of memory if allocated size is not fully used
Fast traversal using loopsNo built-in bounds checking (can cause runtime errors)
Suitable for mathematical operations and algorithmsCannot store different data types (homogeneous only)
Lower overhead compared to dynamic containers like vectorsRequires manual memory management for dynamic arrays

Wrap-up

Understanding arrays in C++ is fundamental for efficient data handling. Arrays allow you to store multiple elements of the same type in a contiguous block of memory, enabling efficient access and manipulation. They are particularly useful when dealing with large datasets or performing operations like sorting, searching, and iteration. By mastering arrays, you lay the groundwork for more advanced data structures and algorithms in C++.

FAQs

Arrays help manage multiple values of the same type efficiently without needing separate variables for each item.

In C++, arrays are stored in contiguous memory locations, making access and iteration faster using index-based logic.

For local arrays, the default values are garbage; for global/static arrays, the default is zero.

Array indexing starts from 0, so the first element is at index 0, not 1, which often confuses beginners.