What is an Array?

An array is a data structure that stores an element of the same data type sequentially. A C++ array has a fixed-size.

You can see an array as a collection of variables of a similar data type. Instead of declaring each variable and assigning it a value individually, you can declare one variable (the array) and add the values of the various variables to it. Each value-added to the array is identified by an index.

In this C++ tutorial, you will learn:

Why do we need arrays?

Arrays are very important in any programming language. They provide a more convenient way of storing variables or a collection of data of a similar data type together instead of storing them separately. Each value of the array will be accessed separately.

Declare an array in C++

Array declaration in C++ involves stating the type as well as the number of elements to be stored by the array. Syntax:

type array-Name [ array-Size ];

Rules for declaring a single-dimension array in C++.

  • Type: The type is the type of elements to be stored in the array, and it must be a valid C++ data type.
  • Array-Name: The array-Name is the name to be assigned to the array.
  • Array-Size: The array-Size is the number of elements to be stored in the array. It must be an integer and greater than 0.

For example, you can create an array named age and store the ages of 5 students as follows:

int age[5];

The array age will store 5 integers representing the ages of different students.

Array Initialization

Array initialization is the process of assigning/storing elements to an array. The initialization can be done in a single statement or one by one. Note that the first element in an array is stored at index 0, while the last element is stored at index n-1, where n is the total number of elements in the array.

In the case of the age array, the first element will be stored at index 0, while the last element will be stored at index 4.

Let us use the age array to demonstrate how array initialization can be done:

int age[5] = {19, 18, 21, 20, 17};

The total number of elements within the { } cannot exceed the value stated within the [ ]. The element 19 is at index 0, 18 at index 1, 21 at index 2, 20 at index 3 and 17 at index 4. If you don't state the number of elements to be stored in the array within [ ], the array will only be large enough to hold the elements added within { }. For example:

int age[] = {19, 18, 21, 20, 17};

The above statement will create exactly the same array as the previous one. You can also assign one element to an array using its index. For example:

age[3] = 20;

The above statement will store the value 20 at index 3 of the array named age. This means that 20 will be the 4th element of the array.

Types of Arrays

There are two types of C++ arrays:

  • One dimensional Array
  • Multi-dimensional Array
  • Pointer to an Array

One-Dimensional Array

This is an array in which the data items are arranged linearly in one dimension only. It is commonly called a 1-D array. Syntax:

datatype array-name[size];
  • The array-name is the name of the array.
  • The size is the number of items to be stored in the array.

For example:

#include <iostream>
using namespace std;

int main()
{
	int age[5] = { 19, 18, 21, 20, 17 };
	for (int x = 0; x < 5; x++)
	{
		cout <<age[x]<<"\n";
	}
}

Output:

Here is a screenshot of the code:

Code Explanation:

  1. Including the iostream header file in our code. It will allow us to read from and write to the console.
  2. Including the std namespace so as to use its classes and functions without calling it.
  3. Calling the main() function inside which the logic of the program should be added.
  4. Start of the body of the main() function.
  5. Declaring an array named age to store 5 integers. The 5 integers have also been initialized.
  6. Create an integer variable x using a for loop.
  7. The beginning of the body of the for loop.
  8. Using the loop variable x to iterate over the values of the array age and print them on the console. The "\n" is a newline character and prints in a new line after every iteration.
  9. End of the body of the for a loop.
  10. End of the body of the main() function.

Multi-dimensional Array

This is an array in which data items are arranged to form an array of arrays. A multi-dimensional array can have any number of dimensions, but two-dimensional and three-dimensional arrays are common. Syntax:

datatype array-name[d1][d2][d3]...[dn];

The array-name is the name of the array that will have n dimensions. For example:

Two Dimensional Array

A 2D array stores data in a list with 1-D array. It is a matrix with rows and columns. To declare a 2D array, use the following syntax:

type array-Name [ x ][ y ];

The type must be a valid C++ data type. See a 2D array as a table, where x denotes the number of rows while y denotes the number of columns. This means that you identify each element in a 2D array using the form a[x][y], where x is the number of row and y the number of columns in which the element belongs.

Here is an example of how to initialize a 2D array:

int a[2][3] = {  
   {0, 2, 1} ,   /*  row at index 0 */
   {4, 3, 7} ,   /*  row at index 1 */
   };

In above example, we have a 2D array which can be seen as a 2x3 matrix. There are 2 rows and 3 columns. The element 0 can be accessed as a[0][1] because it is located at the intersection of row indexed 0 and column indexed 1. The element 3 can be accessed as a[1][2] because it is located at the intersection of row indexed 1 and column indexed 2.

Note that we simply added curly braces to differentiate the different rows of elements. The initialization could also have been done as follows:

int a[2][3] = {0, 2, 1, 4, 3, 7};
   };

The following C++ example demonstrates how to initialize and traverse a 2D array:

#include <iostream>
using namespace std;
int main() 
{
	// a 2x3 array
	int a[3][2] = { {0, 2}, {1, 4}, {3, 7} };

	// traverse array elements

	for (int i=0; i<3; i++)
		for (int j=0; j<2; j++) 
		
		{
			cout << "a[" <<i<< "][" <<j<< "]: ";
			cout << a[i][j] << endl;
		}
	return 0;
}

Output:

Here is a screenshot of the above code:

Code Explanation:

  1. Including the iostream header file in our code. It will allow us to read from and write to the console.
  2. Including the std namespace so as to use its classes and functions without calling it.
  3. Calling the main() function within which code should be added.
  4. Start of the body of the main() function.
  5. A comment. The C++ compiler will skip this.
  6. Declaring a 2D array of 3 rows and 2 columns. Items have also been added to the array.
  7. A comment. The C++ compiler will skip this.
  8. Creating a variable i using a for a loop. This variable will iterate over the row indexes of the array.
  9. Creating a variable j using a for a loop. This variable will iterate over the column indexes of the array.
  10. Start of the body of the loops.
  11. Print the values of variables i and j on the console inside square brackets on the console.
  12. Print out the value stored at index [i][j] of the array a.
  13. End of the body of the loops.
  14. The main() function should return an integer value if the program runs fine.
  15. End of the body of the main() function.

Three –Dimensional Array

A 3D array is an array of arrays. Each element in a 3D array is identified by a set of 3 indexes. To access the elements of a 3D array, we use three for loops. For example:

#include<iostream>
using namespace std;
void main()
{
	int a[2][3][2] = {{{4, 8},{2, 4},{1, 6}}, {{3, 6},{5, 4},{9, 3}}};
	cout << "a[0][1][0] = " << a[0][1][0] << "\n";
	cout << "a[0][1][1] = " << a[0][1][1] << "\n";
}

Output:

Here is a screenshot of the code:

Code Explanation:

  1. Including the iostream header file in our code. It will allow us to read from and write to the console.
  2. Including the std namespace so as to use its classes and functions without calling it.
  3. Calling the main() function inside which the logic of the program should be added.
  4. Start of body of the main() function.
  5. Declaring a 3D array named an of size 2x3x2. The values of the array have also been initialized.
  6. Accessing the item stored at index [0][1][0] of the array and printing it on the console.
  7. Accessing the item stored at index [0][1][1] of the array and printing it on the console.
  8. End of the body of the main() function.

Pointer to an Array

A pointer is a variable that holds an address. Other than using a pointer to store the address of a variable, we can use it to store the address of an array cell. The name of an array constantly points to its first element. Consider the declaration given below:

int age[5];

The age is a pointer to $age[0], the address of the first element of an array named age. Consider the following example:

#include <iostream>
using namespace std;
int main()
{
	int *john;

	int age[5] = { 19, 18, 21, 20, 17 };

	john = age;

	cout << john << "\n";

	cout << *john;
	
}

Output:

Note that the first value of the above output may return a different value depending on the address assigned to the first element of the array in your computer's memory.

Here is a screenshot of the code:

Code Explanation:

  1. Including the iostream header file in our code. It will allow us to read from and write to the console.
  2. Including the std namespace so as to use its classes and functions without calling it.
  3. Calling the main() function inside which the logic of the program should be added.
  4. Start of body of the main() function.
  5. Declaring a pointer variable named *john.
  6. Declaring an integer array named age to store 5 integers. The values of the integers have also been initialized.
  7. Assigning the variable john the value of the address of the item stored in the first index of the array age.
  8. Printing the value of variable john, which is the address of the item stored in the first index of the array age.
  9. Printing the first value stored in the array age.
  10. End of the body of the main() function.

Array names can be used as constant pointers, and the vice versa is also true. This means you can access the value stored at index 3 of array age with *(age + 3). For example:

#include <iostream>
using namespace std;

int main() {
	// an array of 5 elements.
	int age[5] = { 19, 18, 21, 20, 17 };
	int *p;

	p = age;

	// output array values

	cout << "Using pointer: " << endl;

	for (int x=0; x<5; x++) {
		cout << "*(p + " << x << ") : ";
		cout << *(p + x) << endl;
	}
	cout << "Using age as address: " << endl;

	for (int x = 0; x < 5; x++) {
		cout << "*(age + " << x << ") : ";
		cout << *(age + x) << endl;
	}

	return 0;
}

Output:

Here is a screenshot of the code:

Code Explanation:

  1. Including the iostream header file in our code. It will allow us to read from and write to the console.
  2. Including the std namespace so as to use its classes and functions without calling it.
  3. Calling the main() function and start of body of the main() function.
  4. A comment. The C++ compiler will skip this.
  5. Declaring an array named age to store 5 integers.
  6. Creating an integer pointer p.
  7. Assigning p the value of the address of the first element of array age.
  8. A comment. The C++ compiler will skip this.
  9. Print out some text on the console.
  10. Create an integer x using a for a loop. The { marks the beginning of the body of the for a loop.
  11. Print out the values of x combined with some other text on the console.
  12. Print out the values of *(p + x) on the console.
  13. End of the body of the for a loop.
  14. Print out some text on the console.
  15. Create a variable x using a for a loop. The { marks the beginning of the body of the for loop.
  16. Print out the values of x from 0 to 4 alongside some other text.
  17. Print out the values of *(age + x).
  18. End of the body of the for loop.
  19. Return value if the program runs successfully.
  20. End of the body of the main() function.

Accessing the values of an Array

The elements of an array are accessed using their respective indexes. The index of the element to be accessed is added within square brackets [ ] immediately after the array name. For example:

int john = age[2];

In the above example, we are simply stating that john's age is stored at index 2 of the array named age. This means that john's age is the 3rd value in the array age. Here is a complete C++ example that shows how to access and print out this value:

#include<iostream>

using namespace std;

int main()
{

	int age[5] = { 19, 18, 21, 20, 17 };

	int john = age[2];

	cout << "The age of John is:"<<john;
}

Output:

Here is a screenshot of the code:

Code Explanation:

  1. Including the iostream header file in our code. It will allow us to read from and write to the console.
  2. Including the std namespace so as to use its classes and functions without calling it.
  3. Calling the main() function within which code should be added.
  4. Start of a body of the main() function.
  5. Declaring an array named age to store 5 integer elements.
  6. Accessing the value stored at index 2 of array age and storing its value in a variable named john.
  7. Printing the value of variable john on the console alongside other text.

Advantages of an Array in C++

Here, are pros/benefits of using Array in C++:

  • Array elements can be traversed easily.
  • Easy to manipulate array data.
  • Array elements can be accessed randomly.
  • Arrays facilitate code optimization; hence, we can perform much work using less code.
  • Easy to sort array data.

Disadvantages of an Array in C++

  • An array has a fixed size; hence, we cannot add new elements to it after initialization.
  • Allocating more memory than the requirement leads to wastage memory space, and less allocation of memory can create a problem.
  • The number of elements to be stored in an array must be known in advance.

Summary

  • An array is a data structure that stores elements of the same data type.
  • Array elements are stored sequentially.
  • The array elements are denoted using their respective indexes. The first element is at index 0, while the last element is at index n-1, where is the total number of array elements.
  • The declaration of an array involves defining the data types of the array elements as well as the number of elements to be stored in the array.
  • A one-dimensional array stores elements sequentially.
  • A two-dimensional array stores elements in rows and columns.
  • A three-dimensional array is an array of arrays.
  • Elements can be added to an array using their indexes.
  • Array elements are accessed using their indexes.
  • A multi-dimensional array has more than one dimension.
  • The array name points to its first element.
  • Arrays have a fixed size, meaning that new elements cannot be added to the array after its initialization.

 

YOU MIGHT LIKE: