C++ Arrays

In C++, std::array is a container that encapsulates fixed-size arrays. In C++ , the array index starts from 0. We can store only a fixed set of elements in a C++ array.

A collection of related data items stored in adjacent memory places is referred to as an array in the C++ programming language or any other programming language for that matter. Elements of an array can be accessed arbitrarily using its indices. They can be used to store a collection of any type of primitive data type , including int, float, double, char, etc. An array in C++ can also store derived data types like structures, pointers, and other data types, which is an addition. The array representation in a picture is provided below.

Example

Example

#include <iostream>

int main() {

    int numbers[5] = {2, 5, 7, 9, 15};

    // Accessing and displaying elements

    std::cout << "First element: " << numbers[0] << std::endl;

    std::cout << "Second element: " << numbers[1] << std::endl;

    return 0;

}

Output:

Output

First element: 2

Second element: 5

Here, we will discuss about the array declaration, initialization, accessing, and many others.

Array Declaration

In C++, an array is built by first defining the data type , and then the array's name and size, which are both surrounded in square brackets (). This syntax is frequently known as the array subscript operator.

Syntax:

It has the following syntax.

Example

data_type array_name [size];

This declaration creates an array named array_name, which may have a fixed number of elements based on the size specified. The data type of the array char, float, or int determines the types of values it can hold. Once stated, the size of an array cannot be changed dynamically; it is fixed.

For Example: int arr[4];

  • int: The type of element to be stored.
  • arr: Array name.
  • 4: It refers that the array size is 4.

Creates an array named " arr " that can store five integers. However, the elements of an array have no predefined values when it is declared. Unless they are initialized directly, they contain garbage values.

Initializing an Array in C++

An array cannot be used until its elements have been assigned values after it has been declared.

An array can be initialized in two typical ways:

  • Initializing an Array during Declaration
  • Assigning Values after Declaration
  • 1. Initializing an Array during Declaration

Values can be specified inside curly braces {} to initialize an array at declaration time. Commas are used to separate the values.

Example:

Example

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

2. Assigning Values after Declaration

An array can also be initialized by declaring it first, and then giving values to each index independently.

Example:

Example

int num_bers[3]; //Declaration of an array.

// Assigning values to each element

num_bers[0] = 10;  

num_bers[1] = 20;  

num_bers[2] = 30;

Accessing Array Elements in C++

Indexing is the process of accessing an element in an array by following the array name with the index number enclosed in square brackets (). It enables the direct retrieval or modification of particular array elements. The first element is at zero because the index starts at zero, followed by one and next. For example, the expression nameofthe_array[index] references the element at the specified index point.

An element at position n in human counting terms is really situated at n-1 in programming because indexing uses zero-based numbering. Inaccurate data retrieval or crashes may occur when an index is accessed outside of the array's valid range, which leads to undefined behavior. Working with arrays requires proper bounds checking in order to avoid runtime errors.

Syntax:

It has the following syntax.

Example

name_of_the_array[index];

Example:

Let us take an example to illustrate the accessing array elements in C++.

Example

Example

#include <iostream>

using namespace std;

int main() 

{

    // Defining and initializing an array

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

    // Displaying specific elements from the array

    cout << "Starting element at the index 0: " << num_bers[0] << endl;  

    cout << "Middle element at the index 2: " << num_bers[2] << endl;  

    cout << "Last element at the index 4: " << num_bers[4] << endl;   

    // Looping through the array to print all elements

    cout << "Complete array elements: ";

    for (int index = 0; index < 5; index++) 

    {

        cout << num_bers[index] << " ";

    }

    return 0;

}

Output:

Output

Starting element at the index 0: 10

Middle element at the index 2: 30

Last element at the index 4: 50

Complete array elements: 10 20 30 40 50

Explanation:

The five elements {10, 20, 30, 40, 50} in the integer array numbers are initialized upon declaration by the C++ program. The appropriate indexes are used to retrieve and display the elements that are first (numbers[0]), middle (numbers[2]), and last (numbers[4]).

A for loop iterates across the array, printing each entry sequentially. The 'cout' statements ensure that the output is formatted clearly, making it easy to identify the position of each element. The program eventually ends successfully and returns 0, indicating normal execution.

C++ Array with Empty Elements

In C++, an array can hold up to n elements when it is declared with a fixed size of n. However, the behavior of the remaining uninitialized elements is dependent on the array's storage type if fewer than n elements are explicitly initialized. Let us see in the following example.

For example:

Example

int arr[5] = {3, 6, 9};

In this case, just three elements 3, 6, and 9 are explicitly assigned values, despite the array arr having a capacity of 5. In such cases, the uninitialized elements of the array will contain garbage values that happen in memory at the moment of allocation if the array is a local variable (automatic storage).

Example:

Let us take an example to illustrate the C++ array with empty elements.

Example

Example

#include <iostream>

int main() {

    const int size = 4;

    int arr[size]; // Declaration without initialization

    // Displaying uninitialized elements

    std::cout << "Uninitialized array elements:\\n";

    for (int i = 0; i < size; ++i) {

        std::cout << "arr[" << i << "]: " << arr[i] << std::endl;

    }

    return 0;

}

Output:

Output

Uninitialized array elements:

arr[0]: -201085088

arr[1]: 32765

arr[2]: -1660869745

arr[3]: 29498

Taking Inputs from the User and Storing them in an Array in C++

Each element of an array can be retrieved using its index because arrays are collections of elements of the same data type that are stored in contiguous memory locations. In C++, a loop is used to take values from the user after the array is first formed with a fixed size. It allows the array to store user-inputted values.

Example:

Let us take a C++ example of taking Inputs from the User and Storing them in an Array.

Example

Example

#include <iostream>

using namespace std;

int main() 

{

    // Define array size

    const int DATA_LIMIT = 5;

    int recordList[DATA_LIMIT];

    cout << "Enter " << DATA_LIMIT << " values: " << endl;

    // Loop to take input and store values in the array

    for (int q=0; q < DATA_LIMIT; q++)

    {

        cout << "Provide input for position " << q + 1 << ": ";

        cin >> recordList[q];

    }

    cout << "\nStored elements in the array are:\n";

    // Loop to display stored values with their corresponding positions

    for (int track_index = 0; track_index < DATA_LIMIT; track_index++) 

    {

        cout << "Element at index " << track_index << ": " << recordList[track_index] << endl;

    }

    return 0;

}

Output:

Output

Enter 5 values: 

Provide input for position 1: 36

Provide input for position 2: 48

Provide input for position 3: 24

Provide input for position 4: 17

Provide input for position 5: 55

Stored elements in the array are:

Element at index 0: 36

Element at index 1: 48

Element at index 2: 24

Element at index 3: 17

Element at index 4: 55

Explanation:

In this example, the program requests the user to enter five values into an integer array recordList with a predetermined size of DATA_LIMIT (5). After that, a for loop is used to store the data in the array.

The stored values and their corresponding indices are then displayed after iterating through the array once more. This program effectively shows array storage, retrieval, and user input handling in C++.

Finding the Size of an Array in C++ using sizeof Operator

In C++, we can use the sizeof operator to find the size of an array. This operator returns the total amount of memory used by an object, in bytes.

Steps to Find the Size of an Array in C++:

  • Use the sizeof(arrayName) function to determine the overall memory size in bytes that the entire array takes up.
  • Find the Size of a Single Element: Use the sizeof(arrayName[0]) function to see how much memory an individual element in the array contains. Since all of the elements are of the same type, they are all the same size.
  • Determine the Total Number of Elements: The size of a single element divided by the total size of the memory:
  • Example
    
    Total Elements = sizeof(arrayName)/sizeof(arrayName[0])
    
  • Dynamically allocated arrays or pointers cannot be utilized with the sizeof operator. It is only applicable to statically declared arrays.
  • Example:

Let us take a C++ example of finding the Size of an Array using the sizeof Operator in C++.

Example

Example

#include <iostream>

using namespace std;

int main()

{

    int arr[] = {33, 26, 46, 52, 16};  

    // Declaring an array with 5 elements.

    // Calculating size of an array

    int total_Size = sizeof(arr); 

    // Total memory occupied by the array in bytes.

    int singleElement_Size = sizeof(arr[0]);  

    // Memory occupied by single element.

    int array_Length = total_Size / singleElement_Size;  

    // Total umber of elements.

    // Displaying the size in bytes.

    cout << "Total memory occupied by an array: " << total_Size << " bytes" << endl;

    cout << "The size of single element: " << singleElement_Size << " bytes" << endl;

cout << "The total number of elements in the array: " << array_Length << endl;

    return 0;

}

Output:

Output

Total memory occupied by an array: 20 bytes

The size of single element: 4 bytes

The total number of elements in the array: 5

Explanation:

In this example, the sizeof operator is used to determine how much memory and how many elements an array uses overall. First, the sizeof(arr[0]) operator is used to retrieve the memory size of a single element, and the sizeof(arr) is used to determine the total memory used by the array.

It precisely calculates the array length by dividing the overall size by the size of one element. At the end, it ensures an effective method of array size analysis by displaying the array length, the memory utilized by each element, and the total memory utilization.

C++ Array Types

There are mainly two types of arrays in C++ programming:

  • Single Dimensional Array
  • Multidimensional Array
  • C++ Single Dimensional Array

Single dimensional array is a set of elements of the same data type that is stored in a contiguous memory block. It is one of the simplest type of an array that is easy to declare and implement.

Syntax:

It has the following syntax:

Example

element_type array_name [size]

Let us take an example to illustrate the single-dimensional array in C++.

Example

Example

#include <iostream>

using namespace std;

int main() {

    // Declaration and initialization of an array

    int arr[4] = {15, 18, 25, 32};

    // Accessing elements of the array

    cout << "Element at index 2: " << arr[2] << endl;

    // Modifying elements of the array

    arr[1] = 50;

    cout << "Change element at index 1: " << arr[1] << endl;

    // Calculating the sum of all elements

    int sum = 0;

    for (int i = 0; i < 4; i++) {

        sum += arr[i];

    }

    cout << "Sum of all elements: " << sum << endl;

    return 0;

}

Output:

Output

Element at index 2: 25

Change element at index 1: 50

Sum of all elements: 122

C++ Array Example: Traversal using foreach loop

In C++, we can also traverse the array elements using foreach loop. It returns array elements one by one.

Example

Example

#include <iostream>

using namespace std;

int main()

{

 int arr[5]={10, 0, 20, 0, 30}; //creating and initializing array  

        //traversing array  

       for (int i: arr)   

        {  

            cout<<i<<"\n";  

        }  

}

Output:

Output

10

20

30

40

50

Multi-Dimensional Arrays in C++

A multi-dimensional array is a type of array that contains more than one array as its elements. It is a set of items where every element is accessed using multiple indices.

A multi-dimensional array is a type of array that contains more than one array as its elements. It is a set of items where every element is accessed using multiple indices.

Syntax:

It has the following syntax:

Example

data_type array_name[a1][a2]...[an];

Here, a1, a2, and an define the size of every array.

Let us take an example to illustrate the multi-dimensional arrays in C++.

Example

Example

#include <iostream>

using namespace std;

int main() {

    // Declare a 2D array (3 rows, 3 columns)

    int matrix[3][3] = {

        {4, 3, 2},

        {6, 1, 5},

        {9, 7, 8}

    };

    // Display the 2D array

    cout << "Matrix elements are:\n";

    for (int i = 0; i < 3; i++) {

        for (int j = 0; j < 3; j++) {

           cout << matrix[i][j] << " ";

        }

        cout << endl;

    }

    return 0;

}

Output:

Output

Matrix elements are:

4 3 2 

6 1 5 

9 7 8

How to display the sum and average of array elements?

Here, we are taking an example to find the sum and average of array elements in C++.

Example

Example

#include <iostream>  

using namespace std;  

int main() {  

// initialize an array without specifying the size  

double numbers[] = {7, 5, 6, 12, 35, 27};  

double sum = 0;  

double count = 0;  

double average;  

cout << "The numbers are: ";  

 //  print array elements  

 // use of range-based for loop  

 for (const double &n : numbers) {  

  cout << n << "  ";  

//  calculate the sum  

sum += n;  

// count the no. of array elements  

++count;  

  }  

// print the sum  

cout << "\nTheir Sum = " << sum << endl;  

// find the average  

average = sum / count;  

cout << "Their Average = " << average << endl;  

  

  return 0;  

}

Output:

Output

The numbers are: 7 5 6 12 35 27

Their Sum = 92

Their Average = 15.3333

How to display array elements?

Here, we are taking an example to display the array elements in C++.

Example

Example

#include <iostream>  

using namespace std;  

int main() {  

int numbers[5] = {7, 5, 6, 12, 35};  

cout << "The numbers are: ";  

//  Printing array elements  

// using range-based for loop  

for (const int &n : numbers) {  

cout << n << "  ";  

}  

cout << "\nThe numbers are: ";  

//  Printing array elements  

// using traditional for loop  

for (int i = 0; i < 5; ++i) {  

cout << numbers[i] << "  ";  

}  

return 0;  

}

Output:

Output

The numbers are: 7 5 6 12 35

The numbers are: 7 5 6 12 35

Advantages of C++ Array

Several advantages of arrays in C++ are as follows:

1. Code Optimization

Arrays enable us to store multiple values in a single variable, which reduces the requirement for multiple individual variables.

2. Random Access

Array elements may be accessed using an index, which makes the retrieval of elements very fast.

3. Easy to traverse data

In C++, arrays can be traversed very efficiently using the loops.

4. Easy to manipulate data

In C++ arrays, elements can be easily updated, inserted, or deleted.

5. Easy to sort data

Arrays may be sorted easily via several built-in functions, such as std::sort, qsort, etc.

Disadvantages of C++ Array

Several disadvantages of arrays in C++ are as follows:

1. Fixed size

Array sizes are fixed, which means that they cannot be modified once their size is determined.

2. Wastage of Memory

If the size of the array is large and not completely utilized, memory is wasted.

3. Lack of Flexibility

Array sizes are static and cannot be dynamically re-sized. When the array size is declared, its size remains constant throughout the lifetime of the program.

C++ Arrays MCQS

  1. How should an integer array of size 5 be declared in C++?
  • int arr[5];
  • array<int, 5> arr;
  • int arr = {5};
  • int arr(5);
  1. What will the array's last element's index be if it is specified as int arr[10]?
  • Undefined
  1. How do the elements of a C++ array stored in memory?
  • Contiguously
  • Randomly
  • In a linked list format
  • In separate memory blocks
  1. If we access an array element out of its bounds, what happens?
  • Compile-time error
  • Automatic resizing
  • Undefined behavior
  • Zero is returned
  1. Which loop is most commonly used to traverse a C++ array?
  • while loop
  • do-while loop
  • for loop
  • switch statement

Input Required

This code uses input(). Please provide values below: