In this tutorial, you will learn everything about the data structure called an array. With the help of simple examples, you will understand how to declare, initialize and access variables from arrays.
An array is a variable in C++ that can hold multiple values of the same type.
For example,
Assume we have 29 students in a class and we need to save their grades. Instead of making 29 individual variables, we can simply make an array:
double grade[29];
Here in the above example, the grade is an array with a maximum capacity of 29 double-type elements.
Arrays in C++ cannot be changed after they have been declared.
In C/C++ or any other programming language, an array is a group of related data items stored at adjacent memory locations, and its elements can be accessed at random using an array's indices. They can be used to store any type of primitive data type, such as int, float, double, char, and so on. Furthermore, in C/C++, an array is primarily used to store derived data types such as structures, pointers, and so on.
A pictorial representation of an array is given below.
The general syntax of defining array is like-
dataType arrayName[arraySize];
See the below example :
int x[6];
In the above example
int
= It refers to the type of element that will be stored.x
= it refers to the name of the array6
= it refers to the array sizeIn this case array, x[6] creates six adjacent cells in memory which are x[0], x[1], sal[2], x[3], x[4], and x[5] for storing the int type values.
The allocation of arrays starts with a 'null' and consequently the last variable of the series will be stored at x[size -1]. In our example, the first element of the array will be allocated at x[0] and the last element will be allotted at x[5].
Each element in an array is assigned a number in C++. The number is referred to as an array index. Using those indices, we can access array elements.
Syntax in order to access array elements
array[index];
This fig shows the elements of an array in C++
Remember the following:
x[0]
denotes the first element stored at index 0.x[5]
.x[0]
is 2120.x[1]
will then be 2124, x[2]
will be 2128, and so on.int
has a size of 4 bytes.Array initialization is a process of assigning values to the array elements. Array elements must be initialized before they can be used in the program. If they are not properly initialized the program produces unexpected results. Let us understand how arrays are initialized using examples.
It is possible to initialize an array during declaration in C++.
For example: let us declare and initialize an array
int x[6] = {10, 20, 30, 40, 50, 60};
This fig shows the C++ array elements and their data
Another way to initialize an array during its declaration:
int x[] = {10, 20, 30, 40, 50, 60};
We haven't mentioned the array's size here. In such cases, the compiler computes the size automatically.
We can initialize the array after declaration. Let's take an example
int x[3];
x[0] = 10;
x[1] = 20;
x[2] = 30;
An array with no members means empty members. In C++, if an array has a size of n, we can store up to n elements in it. However, in C++ what happens if we store fewer than n elements?
For example
//let us store only 3 elements in the array
int x[6] = {10, 20, 30};
The array x has a size of 6 in this case. However, we've only given it three elements, to begin with.
The compiler assigns random values to the remaining places in such cases. Frequently, this random value is just 0. The empty array members are assigned 0 automatically.
We utilize cout
function to print the values accessed from an array using their indices with the help of loops.
#include
using namespace std;
int main() {
int numbers[5] = {10, 20, 30, 40, 50};
cout << "The numbers : ";
// Printing the array elements
// using the range based for loop
for (int i = 0; i < 5; ++i) {
cout << numbers[i] << " ";
}
return 0;
}
Output:
The numbers : 10 20 30 40 50
In this example for loop was used to iterate from i = 0 to i = 4. We have printed numbers[i] in each iteration.
Let's discuss how to display array elements using range-based loop:
#include
using namespace std;
int main() {
int numbers[5] = {10, 20, 30, 40, 50};
cout << "The numbers : ";
// Printing the array elements
// using the range based for loop
for (const int &n : numbers) {
cout << n << " ";
}
return 0;
}
Output:
The numbers : 10 20 30 40 50
In our range-based loop, we used const int &n
as the range declaration instead of int n
. The const int &n
, on the other hand, is better preferred because:
int n
simply copies the array elements to the variable n
. Memory usage is not effective in this.&n
, on the other hand, uses the array elements' memory addresses to access their data without copying it to a new variable. This is memory-saving.To learn more about this Ranged Loop, check C++ Ranged for Loop.
With the help of the cin
function and loops, we can input values into an array.
Let us write a C++ program that will take the inputs from the user and will be stored in an array.
#include <iostream>
using namespace std;
int main() {
int numbers[5];
cout << " please enter 5 numbers: " << endl;
// store the input from user to an array
for (int i = 0; i < 5; ++i) {
cin >> numbers[i];
}
cout << " So the numbers are: ";
// print the array elements
for (int n = 0; n < 5; ++n) {
cout << numbers[n] << " ";
}
return 0;
}
Output:
please enter 5 numbers: 11 12 17 18 19 So the numbers are: 11 12 17 18 19
We used a for loop once more to iterate from i = 0 to i = 4. In each iteration, we took a user input and stored it in numbers[i].
We then used another for loop to print out all of the array elements.
#include <iostream>
using namespace std;
int main() {
// first initialize an array without specifying its size
double numbers[] = {7, 15, 16, 12, 35, 2};
double sum = 0;
double count = 0;
double average;
cout << "So the numbers are: ";
// print the array elements
// here, use of range-based for loop
for (const double &n : numbers) {
cout << n << " ";
// calculate the sum
sum += n;
// count the number of the 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:
So the numbers are: 7 15 16 12 35 2 Their Sum = 87 Their Average = 14.5
In the program :
Note:
Here in this program, a ranged for loop was used in place of a normal for loop.
The size of the array determines the number of iterations in a normal for loop, which must be specified.
A ranged for loop, on the other hand, does not require such kind of specifications.
If we declare a 10-element array, the array will contain elements from 0 to 9.
However, attempting to access the element at index 10 or higher will result in Undefined Behaviour. This is what is known as the array out of bounds in C++.
When we have a small number of objects, then we can use normal variables (v1, v2, v3, etc.), but when we have a very large number of instances, it will become very difficult in order to manage them with the normal variables. So the main idea behind the usage of an array is to represent multiple instances in a single variable.
To practice more programs in arrays refer to our sample programs.