C++ Arrays - C++ Programming Tutorial
C++ Course / Arrays / C++ Arrays

C++ Arrays

BLUF: Mastering C++ Arrays is a critical step in becoming a proficient C++ developer. This lesson provides a deep dive into the syntax, performance considerations, and real-world applications of this concept.
Key Performance Insight: C++ Arrays

C++ is renowned for its efficiency. Learn how C++ Arrays enables low-level control and high-performance computing in the tutorial below.

In C++, std::array serves as a container that wraps around arrays of a predetermined size. In C++, array indexing commences at 0, restricting the storage of a specific number of elements within a C++ array.

A group of interconnected data elements stored in contiguous memory locations is known as an array in the C++ programming language or any other programming language. Elements within an array can be accessed randomly by using their respective indices. Arrays are capable of holding a variety of primitive data types such as int, float, double, char, and more. In addition to primitive types, C++ arrays can also accommodate complex data structures like structures, pointers, and various other derived data types. Below is a visual representation illustrating how an array is structured:

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 explore array declaration, initialization, accessing, and various other operations.

Array Declaration

In C++, constructing an array involves specifying the data type initially, followed by declaring the array's name and size enclosed within square brackets (). This specific syntax is commonly referred to as the array subscript operator.

Syntax:

It has the following syntax.

Example

data_type array_name [size];

This statement establishes an array called array_name, which could contain a set quantity of elements determined by the specified size. The array's data type, whether char, float, or int, dictates the kind of data it can store. Once defined, the array's size remains constant and cannot be altered dynamically.

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.

Declare an array called "arr" capable of storing five integers. It's important to note that arrays do not have predefined values upon declaration and will contain random values unless explicitly initialized.

Initializing an Array in C++

An array must have its elements assigned values before it can be utilized, following its declaration.

An array can be created in two common methods:

  • Initialization of an Array during Declaration
  • Setting Values post Declaration
  • 1. Initializing an Array during Declaration

Values can be defined within curly brackets {} to set up an array during declaration. Commas are employed to delimit the values.

Example:

Example

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

2. Assigning Values after Declaration

An array may also be initialized by first declaring it, followed by assigning values to each index individually.

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++

Accessing an element within an array is accomplished through indexing, where the array name is appended with the index number enclosed in square brackets (). This mechanism facilitates the specific retrieval or alteration of individual array elements. The initial element is positioned at zero due to the zero-based index, with subsequent elements following in numerical order. To illustrate, the syntax nameofthe_array[index] indicates the element located at the designated index position.

In human counting, an item at the nth position corresponds to n-1 in programming due to zero-based indexing. Accessing an index beyond the valid range of an array can result in incorrect data retrieval or system crashes, causing unpredictable outcomes. To prevent runtime errors, it is crucial to implement accurate bounds checking when manipulating arrays.

Syntax:

It has the following syntax.

Example

name_of_the_array[index];

Example:

Let's consider an example to demonstrate how to access elements in an array using 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 set of five elements {10, 20, 30, 40, 50} within the integer array numbers are set with initial values during declaration in the C++ program. Retrieval and display of the first (numbers[0]), middle (numbers[2]), and last (numbers[4]) elements utilize the correct indexes.

A for loop cycles through the array, displaying each item in order. The 'cout' commands maintain well-organized output, aiding in the clear distinction of individual elements. The execution of the program concludes without errors, returning 0 to signify a standard run.

C++ Array with Empty Elements

In C++, a fixed-size array can store a maximum of n elements upon declaration. The handling of uninitialized elements beyond the explicitly initialized ones depends on the storage type of the array when fewer than n elements are provided with values. An illustration of this behavior is demonstrated below.

For example:

Example

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

In this scenario, only elements 3, 6, and 9 have been given specific values, even though the array arr can hold up to 5 elements. When this occurs, any elements in the array that have not been explicitly initialized will hold random values that were present in memory at the time of allocation, especially if the array is a local variable stored in automatic memory.

Example:

Let's consider a scenario to demonstrate the C++ array containing uninitialized 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 item within an array can be accessed by its index as arrays are groupings of elements of identical data types that are saved in sequential memory positions. In C++, a loop is employed to receive input values from the user once the array has been initialized with a set size, enabling the storage of user-provided data within the array.

Example:

Let's consider a C++ illustration where user inputs are gathered and stored 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 instance, the software prompts the user to input five values into an integer array named recordList, which has a fixed size defined as DATA_LIMIT (5). Subsequently, a for loop is employed to save the information within the array.

The program effectively demonstrates array storage, retrieval, and user input handling in C++ by showcasing the stored values along with their respective indices upon iterating through the array again.

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

In C++, the sizeof operator can be utilized to determine the size of an array. This operator provides the total memory occupied by an object, measured 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 assigned arrays or pointers are incompatible with the sizeof function. This operator is restricted to statically defined arrays.
  • Example:

Let's consider a C++ illustration demonstrating how to determine 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 instance, the sizeof function is employed to ascertain the total memory allocation and the number of elements occupied by an array. Initially, the sizeof(arr[0]) function is utilized to fetch the memory size of an individual element, while the sizeof(arr) function is employed to calculate the overall memory consumption of the array.

It accurately determines the length of an array by dividing the total size by the size of a single element. This guarantees an efficient approach to analyzing array size, showcasing the array length, memory consumption per element, and the total memory usage.

C++ Array Types

There are primarily two categories of arrays in C++ development:

  • One-Dimensional Array
  • Multidimensional Array
  • C++ Single Dimensional Array

A one-dimensional array consists of items of the identical data type arranged in a sequential memory location. It represents a basic form of an array that is straightforward to define and execute.

Syntax:

It has the following syntax:

Example

element_type array_name [size]

Let's consider an example to demonstrate the one-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 iterate through the array elements using a foreach loop, which retrieves each element of the array sequentially.

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 an array that includes multiple arrays as its elements. This data structure allows access to individual elements using multiple indices.

A multidimensional array is an array that comprises multiple arrays as its elements, requiring multiple indices to access each element within the collection.

Syntax:

It has the following syntax:

Example

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

Here, a1, a2, and an represent the dimensions of each array.

Let's consider a scenario to demonstrate the concept of multi-dimensional arrays in the C++ programming language.

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 will demonstrate how to calculate the sum and average of elements within an array using 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?

In this instance, we will demonstrate how to showcase the elements of an array using 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

Numerous benefits of arrays in C++ include:

1. Code Optimization

Arrays allow us to store numerous values within a single variable, thereby decreasing the need for multiple separate variables.

2. Random Access

Array elements can be retrieved quickly by utilizing an index to access them, resulting in efficient element retrieval.

3. Easy to traverse data

In C++, arrays can be efficiently iterated through using loops.

4. Easy to manipulate data

In C++ arrays, it is straightforward to modify, add, or remove elements.

5. Easy to sort data

Arrays can be effortlessly sorted using various pre-existing functions like std::sort, qsort, and others.

Disadvantages of C++ Array

Numerous drawbacks of arrays in C++ include:

1. Fixed size

Arrays have a fixed size, meaning that it cannot be altered once it is established.

2. Wastage of Memory

If the array is sizable and not fully utilized, it results in wastage of memory.

3. Lack of Flexibility

Arrays have fixed sizes and cannot be resized dynamically. Once the size of an array is defined, it stays constant for the entire duration 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);

a) An array "arr" with a size of 10 will have the last element's index as 9.

  • The behavior is 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:

Logic Practice
Install Logic Practice
Add to home screen for a faster app-like experience