Array in C++

Challenge Inside! : Find out where you stand! Try quiz, solve problems & win rewards!

Video Tutorial

Array Introduction

Overview

An array is a collection of data belonging to the same datatype and category, stored in contiguous memory locations. Indexing of arrays in C++ always starts from 0 and ends at one less than the size of the array. There are many ways to access the elements of an array. One of them is using pointers. Pointer to the name of an array gives the first element of the array. The arrays having more than one dimension are known as multidimensional arrays.

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.

Scope

  • The article defines the C++ array, its need, declaration, and initialization with various examples.
  • Advantages, disadvantages, and facts about arrays are also explained.
  • The article also introduces and illustrates multidimensional arrays along with examples.
  • The relation between arrays and pointers is described with examples.
  • Vectors are also defined with examples and their advantages over arrays.

Arrays in C++

  • 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. The indexing in the arrays always starts from 0.
  • The memory locations in an array are contiguous, which means that the difference between adjacent addresses is equal to the size of elements belonging to that datatype.

Why Do We Need Arrays?

Multiple variables are required to store multiple values which may belong to a similar category and may have the same datatype. The use of many variables creates a lot of confusion and increases the program's length.

The addresses of the different variables are also far apart, and there is no connection between the addresses of the two variables. Therefore, arrays come into the picture to use a single variable for different values belonging to the same category and datatype.

Example:
Consider a situation where marks of 5 students are required to store without using arrays. Here, five different variables are created to store the marks of 5 students. However, a single array of 5 elements can store the marks of 5 students. There is no need to create and remember the names of 5 different variables in the program.

Program to Store the marks of 5 students without using arrays

Output:

Explanation:
In the above program, five different variables are declared and initialized to store marks of 5 students.

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

Initializing Arrays in CPP

The common syntax for the initialization of a C++ array:

Example:

Explanation:

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

When the size of an array is unknown, we can use the below syntax for initializing the array. Here, the compiler itself calculates the size of the array and assigns it to the array.

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.

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:

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.

Advantages of an Array in C++

  • Elements of an array can be accessed in O(1) time.
  • Minimizes the length of the code by putting values of multiple variables into a single array.
  • Updation of array elements is done in constant time.
  • Arrays can be easily traversed using a single loop.
  • The memory of array elements are very close to one another, and therefore, the cache can easily access them from the CPU.
  • Managing and sorting array elements requires fewer lines of code.

Disadvantages of an Array in C++

  • The size of an array can not be increased or decreased once defined during declaration. The use of arrays is not suitable when size is not defined earlier.
  • Arrays are homogeneous. All the elements of an array should belong to the same datatype.
  • The process of insertion and deletion of elements in arrays is costly. This is because of enhanced complications in traversing to the point of insertion and deletion and shifting of array elements. New memory allocation creates the process of insertion more complex.
  • Garbage value is thrown while accessing any index out of range. Arrays in C++ do not throw index-bound errors during compile time.

Facts about Array in C++

  • The memory occupied by an array can easily be calculated by the product of the size of an array and memory allocated to any element of the datatype to which the array belongs.
  • The difference between the memory locations of the adjacent array elements is equal to the size of the datatype.
  • Pointer to the name of an array gives the first element of the array.
  • Array elements can be accessed through pointers. For example: *(arr+5) is equivalent to arr[5].

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.

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.

Vector in C++

Vectors are one of the containers in C++ that stores 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.

Iterators are used for accessing and traversing the vector elements, which are located at contiguous storage.

  • Insertion in the vector is done at the last element.
  • The process of insertion requires differential time due to resizing of vector and allocation of memory to the new element.
  • Deletion of the last element is performed in constant time as there is no change in the size of the vector.
  • Insertion and deletion at any position of vector except the last element take linear time.

Example:

Output:

Explanation:

  • #include<vector>: It is a library that is required in the code to use vectors.
  • vector<int> a: Declaration of vectors in c++
  • push_back(): It is a function to insert the elements in the vector from the back or as the last element.
  • size(): It is a function that returns the number of elements in the vector.

In the above code, a vector is declared, and elements are inserted in it dynamically. A loop is used to traverse the elements of the vector.

Check out this article to learn more about Vector in C++.

Advantages of Vector over Array in C++

  • The size of arrays is fixed once declared while vectors are resizable as their allocation is performed on heap memory.
  • Arrays are passed to a function along with their size, while vectors contain variables that keep track of their size.
  • Deallocation of arrays, when declared dynamically, needs to be done explicitly while deallocation of vectors is done automatically from the heap memory.
  • Arrays cannot be copied using the assignment operator, while vectors can be easily copied using the assignment operator.
  • Statically allocated arrays cannot be returned from a function directly, while vectors can be returned from a function.

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.

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 require 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 stores data like arrays but can variate its 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.