Array in C++

Video Tutorial
FREE
Array Introduction thumbnail
This video belongs to
C++ Course: Learn the Essentials
14 modules
Certificate
Topics Covered

An array is a collection of data belonging to the same datatype and category, stored in contiguous memory locations. The size of the array remains fixed once declared. For example, If we need to manage the marks of numerous students, arrays simplify the task by allowing us to store and organize data for a large number of students efficiently, eliminating the need for multiple individual variables.

Properties of Array in C++

  1. Arrays store data of the same data type in a contiguous memory location.
  2. Indexing begins at 0, with the first element at the 0th index.
  3. Elements are accessed using their indices.
  4. Array size remains constant once declared.
  5. Arrays can have multiple dimensions for complex data structures.
  6. The sizeof operator determines the number of elements in an array.
  7. Size of elements in an array can be found by subtracting adjacent addresses.

Declaring an array in C++

The syntax for the declaration of C++ array:

Example:

Explanation:

  • float: Datatype of the array
  • a: Name of the array
  • 10: Size of the array

Initializing Arrays in C++

Initialization TypeExampleDescription
Initialize Array with Values in C++int arr[5] = {1, 2, 3, 4, 5};Initializes an array with specified values.
Initialize Array with Values and without Sizeint arr[] = {1, 2, 3, 4, 5};Array size is determined by the number of elements.
Initialize Array after Declaration (Using Loops)for (int i = 0; i < N; i++) { arr[i] = value; }Initializes array elements using a loop, useful for user input.
Initialize an array partially in C++int partialArray[5] = {1, 2};Initializes only the specified elements, others are set to 0.
Initialize the array with zero in C++int zero_array[5] = {0};Initializes all elements to 0, can be overridden individually.

Example:

Explanation:

  • int: Datatype of the array
  • a: Name of the array
  • 5: Size of the array
  • {10,10,10,10,10}: Elements of the array enclosed in curly brackets

Initializing Arrays in CPP

Program to Store the Marks of 5 students using Arrays

Output:

Explanation:
In the above code, the marks of 5 students are stored in an array named student, which can be accessed using the indexes of the array.

Accessing Array Elements

Array elements are accessed using indexes. In C++, array indexing starts from 0, which implies that the first element in the array is placed at zeroth index. If an array has five elements, then indexing will be done from 0 to 4.

Syntax:

Example:

Output:

Explanation:
An array is declared, and values are assigned to each array index. A for loop is used to print values present at those array indexes.

C++ Array With Empty Members

We can also initialize C++ Arrays with fewer elements than the size of the array. The provided elements get stored in the array, and the remaining elements get initialized with 0.

Example:

Explanation:
Here, an array a is declared with datatype int providing space to store 10 elements but only 5 elements have been initialized. So, the remaining array indexes get filled with 0. Internally, the array looks like:

Passing Array to Function in C++

Passing an array to a function in C++ involves treating the array as a pointer to its first element, allowing the function to access and manipulate the array's contents. Here's an example to illustrate this concept:

In this example, the findSum function takes an integer array arr and its size as arguments. It calculates the sum of all elements in the array and returns the result. When calling this function in the main function, we pass the marks array and its size (10) as arguments. Inside the findSum function, the array is accessed using the array notation, and the sum is calculated. For more details: Passing Array to Function in C++

Multidimensional Arrays

Multidimensional arrays are generally referred to as an array of arrays. They contain arrays of the same size in their indexes. Each dimension in the multidimensional array has a fixed size. The number of elements in a multidimensional array can be calculated by the product of the sizes of all the dimensions in the multidimensional array. Two-dimensional and three-dimensional arrays are commonly used in C++ programming.

The syntax for multidimensional array:

Explanation:

  • dataType: Type to which the multidimensional array belongs
  • arrayName: Name of the multidimensional array
  • size1d....sizeNd: Size of each dimension

Example:

Two-Dimensional Array

A two-dimensional array represents the tabular form of data in rows and columns. A 2-D array consisting of numbers is known as a matrix that helps solve various mathematical problems.

Elements in two-dimensional arrays are accessed by arrayName[i][j] where ‘i’ represents the row number and ‘j’ represents the column number. The indexing of rows and columns starts from 0 and ends at row-1 and column-1, respectively.

Example:

Output:

Explanation:
In the above code, a 2-d array is declared and initialized with six elements that automatically get adjusted in the rows and columns. There are two loops for accessing rows and columns of the 2-d array. All the elements of the 2-d array are displayed in tabular format.

Three-Dimensional Array

Three-dimensional arrays contain an array inside an array of arrays. It is formed when each element of a two-dimensional array contains an array.

Elements in three-dimensional arrays are accessed by arrayName[i][j][k] where ‘i’ represents the row number, ‘j’ represents the column number, and ‘k’ represents the inside array number.

Example:

Output:

Explanation:

In the above code, a 3-d array is declared and initialized with 12 elements that automatically get adjusted in the rows, columns, and inner array. There are three loops for accessing rows, columns, and the inner array of the 3-d array. All the elements of the 3-d array are displayed in a tabular format of Column x Inner Array for each row.

For more details: What are Multidimensional Arrays in C++ ?

Relation Between Array and Pointers

Pointers are the variables that store the address of the memory location of objects. Pointers and arrays are related by various factors.

  • Pointer to array name is equal to the first element of the array.
  • Pointers can also be used to access array elements.
  • Pointers can store the address of the array elements.
  • Arrays are passed as pointers to the functions as arguments.

Following are examples to illustrate the relationship between pointers and arrays:

Program to illustrate Pointer to Array Name is Equal to the First Element of the Array

Output:

Explanation:
In the above code, an array is declared and initialized with six elements. Pointer to the name of the array is used to print the first element of the array.

Program to illustrate the Use of Pointers to access Array elements

Output:

Explanation:
An array is declared and initialized with six elements. A loop is used to traverse the array, and pointers are used to access the array elements.

Program to illustrate Pointers to store address of the Array elements

Output:

Explanation: An array is declared and initialized with six elements. A pointer is used to store the address of the 3rd element of the array.

Program to illustrate passing of arrays as Pointers to Functions as argument

Output:

Explanation:
An array is declared and initialized with six elements. The array is passed to a function. The function receives the array as a pointer and accesses the elements of the array. For more details: Difference between Arrays and Pointers in C++

C++ Array Out of Bounds

While accessing the index, which is not in the range of the array, in C++, the array does not throw any kind of exception like Array Out of Bounds. Instead of that, it returns garbage value.

Example:

Output:

Explanation:
In the above code, an array of 5 elements has been declared and initialized. Printing elements at index 7 and -2 to show that C++ arrays do not throw exceptions while accessing indexes out of range.

Advantages of using arrays in C++:

  1. Efficient Storage: Arrays allocate memory for elements in a contiguous block, minimizing memory overhead.

  2. Random Access: Elements in an array can be accessed directly using their index, providing quick and efficient data retrieval.

  3. Easy Iteration: Arrays facilitate straightforward iteration through elements using loops, making operations on multiple elements simple.

  4. Compact Code: Arrays reduce the need for numerous individual variables, resulting in cleaner and more concise code.

  5. Improved Performance: Due to their memory layout, arrays can lead to faster execution compared to other data structures for certain tasks.

Disadvantages of Arrays in C++:

  1. Fixed Size: Arrays have a fixed size, making it challenging to dynamically resize them if the number of elements changes.

  2. Inefficient Insertions and Deletions: Inserting or deleting elements in the middle of an array requires shifting elements, leading to inefficient operations.

  3. Wasteful Memory Usage: Arrays allocate memory for the maximum possible number of elements, potentially wasting memory when not all slots are used.

  4. Limited Functionality: Arrays provide basic functionality and lack advanced features like dynamic resizing or built-in methods for common operations.

Conclusion

  • An array is a collection of data represented by a single variable that belongs to the same datatype and category, stored in the contiguous memory location.
  • Accessing elements of the C++ array requires constant time, while insertion and deletion require linear time.
  • Multidimensional arrays are generally referred to as an array of arrays. A two-dimensional array represents the tabular form of data in rows and columns.
  • Pointer to the name of an array gives the first element of the array, and the array elements can be accessed through pointers.
  • Vectors are one of the containers in C++ that store data like arrays but can variate their size automatically when operations like insertion and deletions are performed, with their storage being handled automatically by the container.
  • C++ arrays throw garbage values instead of exceptions while accessing the index, which is not in range.