Close
Close

Arrays in C++


In simple English, array means collection. In C++ also, an array is a collection of similar types of data. eg.- an array of int will contain only integers, an array of double will contain only doubles, etc.

Why Array?


Suppose we need to store the marks of 50 students in a class and calculate the average marks. Declaring 50 separate variables will do the job but no programmer would like to do so. And here comes the array in action.

How to declare an array


datatype array_name [ array_size ];

For example, take an integer array 'n'.

int n[6];

n[ ] is used to denote an array named 'n'.

So, n[6] means that 'n' is an array of 6 integers. Here, 6 is the size of the array i.e., there are 6 elements of array 'n'.

Giving array size i.e. 6 is necessary because the compiler needs to allocate space to that many integers. The compiler determines the size of an array by calculating the number of elements of the array.

Here 'int n[6]' will allocate space to 6 integers.

We can also declare an array by another method.

int n[ ] = { 2,3,15,8,48,13 };

In this case, we are declaring and assigning values to the array at the same time. Hence, no need to specify the array size because the compiler gets it from { 2,3,15,8,48,13 }.

Following is the pictorial view of the array.

element 2 3 15 8 48 13
index 0 1 2 3 4 5

0,1,2,3,4 and 5 are the indices. It is like these are the identities of 6 different elements of the array. Index starts from 0. So, the first element has index 0. We access the elements of an array by writing array_name[index].

Index of an array starts with 0.

Here,
n[0] is 2
n[1] is 3
n[2] is 15
n[3] is 8
n[4] is 48
n[5] is 13

Initializing an array


By writing int n[ ]={ 2,4,8 }; , we are initializing the array.

But when we declare an array like int n[3]; , we need to assign the values to it separately. Because 'int n[3];' will definitely allocate the space of 3 integers in the memory but there are no integers in that.

To assign values to the array, assign a value to each of the element of the array.

n[0] = 2;
n[1] = 4;
n[2] = 8;

It is just like we are declaring some variables and then assigning the values to them.

int x,y,z;
x=2;
y=4;
z=8;

Thus, the two ways of initializing an array are:

int n[ ]={ 2,4,8 };

and the second method is declaring the array first and then assigning the values to its elements.

int n[3];

n[0] = 2;
n[1] = 4;
n[2] = 8;

You can understand this by treating n[0], n[1] and n[2] as different variables you used before.

Just like a variable, an array can be of any other data type also.

float f[ ]= { 1.1, 1.4, 1.5};

Here, f is an array of floats.

First, let's see the example to calculate the average of the marks of 3 students. Here, marks[0], marks[1] and marks[2] represent the marks of the first, second and third student respectively.

#include <iostream>
int main(){

	using namespace std;

	int marks[3];
	float average;
	cout << "Enter marks of first student" << endl;
	cin >> marks[0];
	cout << "Enter marks of second student" << endl;
	cin >> marks[1];
	cout << "Enter marks of third student" << endl;
	cin >> marks[2];

	average = ( marks[0] + marks[1] + marks[2] )/ 3.0;
	cout << "Average marks : " << average << endl;

	return 0;
}
Output
Enter marks of first student
23
Enter marks of second student
25
Enter marks of third student
31
Average marks : 26.3333

Here, you have seen a working example of array. We treated the array in the exact similar way as we had treated normal variables.

In the above example, two points should be kept in mind.
The average value should be of type 'float' because the average of integers can be float also.
Secondly, while taking out the average, sum of the numbers should be divided by 3.0 and not 3, otherwise, you will get the average value as integer and not float.

We can also use for loop as in the next example.

#include <iostream>
int main(){

	using namespace std;

	int n[10]; /* declaring n as an array of 10 integers */
  	int i,j;

  	/* initializing elements of array n */
	 for ( i = 0; i<10; i++ )
	 {
	 	cout << "Enter value of n[" << i << "]"<< endl;
    	        cin >> n[i];
  	}

  	/* printing the values of elements of array */
  	for (j = 0; j < 10; j++ )
  	{
    	       cout << "n[" << j << "] = " << n[j] << endl;
  	}

	return 0;
}
Output
Enter value of n[0]
23
Enter value of n[1]
25
Enter value of n[2]
31
Enter value of n[3]
1
Enter value of n[4]
33
Enter value of n[5]
35
Enter value of n[6]
76
Enter value of n[7]
47
Enter value of n[8]
74
Enter value of n[9]
45
n[0] = 23
n[1] = 25
n[2] = 31
n[3] = 1
n[4] = 33
n[5] = 35
n[6] = 76
n[7] = 47
n[8] = 74
n[9] = 45

The above code was just to make you familiar with using loops with an array because you will be doing this many times later.

The code is simple, i and j starts from 0 because index of an array starts from 0 and goes up to 9 ( for 10 elements ). So, i and j goes up to 9 and not 10 ( i<10 and j<10 ) . So in the above code, n[i] will be n[0], n[1], n[2], ...., n[9].

There are two for loops in the above example. In the first for loop, we are taking the values of the different elements of the array from the user one by one. In the second for loop, we are printing the values of the elements of the array.

Let's go to the first for loop. In the first iteration, the value of i is 0, so 'n[i]' is 'n[0]'.Thus by writing cin >> n[i];, the user will be asked to enter the value of n[0]. Similary in the second iteration, the value of 'i' will be 1 and 'n[i]' will be 'n[1]'. So 'cin >> n[i];' will be used to input the value from the user for n[1] and so on. 'i' will go up to 9, and so indices of the array ( 0,1,2,...,9).

Array allocates contiguous memory. Thus if the address of the first element of an array of integers is X then the address of the second element will be X+4 (4 is the size of one integer) ) and third will be X+4+4 and so on. This means that the memories of all elements of an array are allocated together and are continuous.

Pointer to Arrays


Till now, you have seen how to declare and assign values to an array. Now, you will see how we can have pointers to arrays too. But before starting, we are assuming that you have gone through Pointers. If not, then first read the topic Pointers and practice some problems from the Practice section.

As we all know that pointer is a variable whose value is the address of some other variable i.e., if a variable y points to another variable x means that the value of the variable 'y' is the address of 'x'.

Similarly, if we say that a variable y points to an array n, then it means that the value of 'y' is the address of the first element of the array i.e., n[0]. So, y is the pointer to the array n.

Array name is a pointer to the first element of the array.

If p is a pointer to the array age, then it means that p(or age) points to age[0].

int age[50];
int *p;
p = age;

The above code assigns the address of the first element of age to p.

Now, since p points to the first element of the array age, *p is the value of the first element of the array.

Since *p refers to the first array element, *(p+1) and *(p+2) refers to the second and third elements respectively and so on.

So, *p is age[0], *(p+1) is age[1], *(p+2) is age[2].

Similarly, *age is age[0] ( value at age ), *(age+1) is age[1] ( value at age+1 ), *(age+2) is age[2] ( value at age+2 ) and so on.

That's all in pointer to arrays.

Now let's see some examples.

#include <iostream>
int main(){

	float n[5] = { 20.4, 30.0, 5.8, 67, 15.2 }; /* declaring n as an array of 5 floats */
  	float *p; 		/* p as a pointer to float */
  	int i;
  	p = n; 		/* p now points to array n */
  	/* printing the values of elements of array */
  	for (i = 0; i < 5; i++ )
  	{
    	std::cout << "*(p + " << i << ") = " << *(p + i) << std::endl;/* *(p+i) means value at (p+0),(p+1)...*/
  	}

	return 0;
}
Output
*(p + 0) = 20.4
*(p + 1) = 30
*(p + 2) = 5.8
*(p + 3) = 67
*(p + 4) = 15.2

Since p is pointing to the first element of array, so, *p or *(p+0) represents the value at p[0] or the value at the first element of p. Similarly, *(p+1) represents value at p[1]. So *(p+3) and *(p+4) represent the values at p[3] and p[4] respectively. So, accordingly, we will get the output.

The above example sums up the above concepts. Now, let's print the address of the array and also individual elements of the array.

#include <iostream>
int main(){

	int n[4] = { 20, 30, 5, 67 }; /* declaring n as an array of 4 integers */
  	int *p; /*a pointer*/
  	int i;
  	p = n; /*p is pointing to array n*/
  	/* printing the address of array */
    std::cout << "Address of array n = " << p << std::endl; /*p points to array means store address of first element of array*/
  	/* printing the addresses of elements of array */
  	for (i = 0; i < 4; i++ )
  	{
    		std::cout << "Address of n[" << i << "] = " << &n[i] << std::endl;
  	}

	return 0;
}
Output
Address of array n = 0xfffe2c0c
Address of n[0] = 0xfffe2c0c
Address of n[1] = 0xfffe2c10
Address of n[2] = 0xfffe2c14
Address of n[3] = 0xfffe2c18

In the above example, we saw that the address of the first element of n and p is the same. We also printed the values of other elements of the array by using (p+1), (p+2) and (p+3).

Passing the whole Array in Function


In C++, we can pass an element of an array or the full array as an argument to a function.

Let's first pass a single array element to a function.

#include <iostream>
void display(int a)
{
	std::cout << a << std::endl;
}
int main(){
	int n[ ] = { 20, 30, 23, 4, 5, 2, 41, 8 };
  	display(n[2]);
	return 0;
}
Output
23

Passing an entire Array in a Function


We can also pass a whole array to a function by passing the array name as argument. Yes, the trick is that we will pass the address of array, that is the address of the first element of the array. Thus, by having the pointer of the first element, we can get the entire array as we have done in the above examples.

passing array to function in C++

Let's see an example to understand this.

#include <iostream>

float average(float a[])
{
    int i;
    float avg, sum=0;
    for(i=0;i<8;++i)
    {
        sum+= a[i];
    }
    avg = sum/8;
    return avg;
}

int main(){
	float b, n[ ] = { 20.6, 30.8, 5.1, 67.2, 23, 2.9, 4, 8 };
	b = average(n);
  	std:: cout << "Average of numbers = " << b << std::endl;
	return 0;
}
Output
Average of numbers = 20.2

average(float a[]) - It is the function that is taking an array of float. And rest of the body of the function is performing accordingly.

b = average(n) - One thing you should note here is that we passed n. And as discussed earlier, n is the pointer to the first element or pointer to the array n[]. So, we have actually passed the pointer.

In the above example in which we calculated the average of the values of the elements of an array, we already knew the size of the array i.e., 8.

Suppose, we are taking the size of the array from the user. In that case, the size of the array is not fixed. Here, we need to pass the size of the array as the second argument to the function.

#include <iostream>

float average(float a[], int size)
{
    int i;
    float avg, sum=0;
    for(i=0;i<size;i++)
    {
        sum+= a[i];
    }
    avg = sum/size;
    return avg;
}

int main(){
	using namespace std;
	int size,j;
  	cout << "Enter the size of array" << endl;
  	cin >> size;
  	float b, n[size];
  	for(j=0; j<size; j++)
  	{
    	cout << "Value of n[" << j << "] : " << endl;
    	cin >> n[j];
  	}
  	b = average(n, size);
  	cout << "Average of numbers= " << b << endl;
	return 0;
}
Output
Enter the size of array
4
Value of n[0] :
47
Value of n[1] :
74
Value of n[2] :
45
Value of n[3] :
56
Average of numbers= 55.5

The code is similar to the previous one except that we passed the size of array explicitly - float average(float a[], int size).

We can also pass an array to a function using pointers. Let's see how.

#include <iostream>

using namespace std;

void display(int *p)
{
    int i;
    for(i=0;i<8;++i)
    {
        cout << "n[" << i << "] = " << *p << endl;
        p++;
    }
}

int main(){
    int size,j;
    int n[ ] = { 1, 2, 3, 4, 5, 6, 7, 8 };
    display(n);
    return 0;
}
Output
n[0] = 1
n[1] = 2
n[2] = 3
n[3] = 4
n[4] = 5
n[5] = 6
n[6] = 7
n[7] = 8

In the above example, the address of the array i.e., address of n[0] is passed to the formal parameters of the function.

void display(int *p) - This means that the function 'display' is taking a pointer of an integer and not returning any value.

Now, we passed the pointer of an integer i.e., pointer of array n[] - 'n' as per the demand of our function 'display'.
Since p is the address of the array n[] in the function 'display', i.e., the address of the first element of the array (n[0]), therefore *p represents the value of n[0]. In the for loop in the function, p++ increases the value of p by 1. So when i=0, the value of *p gets printed. Then p++ increases *p to *(p+1) and thus in the second loop, the value of *(p+1) i.e. n[1] gets printed. This loop continues till i=7 when the value of *(p+7) i.e. n[7] gets printed.

passing array to function

For-each loop


There is a new form of for loop which makes iterating over arrays easier. It is called for-each loop. It is used to iterate over an array. Let's see an example of this.

#include <iostream>

int main()
{
	using namespace std;
	int ar[] = { 1,2,3,4,5,6,7,8,9,10 };
	for (int m : ar)
	{
		cout << m << endl;
	}
	return 0;
}
Output
1
2
3
4
5
6
7
8
9
10

This is very simple. Here, the variable m will go to every element of the array ar and will take its value.
So, in the first iteration, m is the 1st element of array ar i.e. 1.
In second iteration, it is the 2nd element i.e. 2 and so on. Just focus on the syntax of this for loop, rest of the part is very easy.

2D Arrays


What if arrays are 2 dimensional?

Yes, 2-dimensional arrays also exist and are generally known as matrix. These consist of rows and columns.

Before going into its application, let's first see how to declare and initialize a 2 D array.

Similar to one-dimensional array, we define 2-dimensional array as below.

int a[2][4];

Here, a is a 2-D array of type int which consists of 2 rows and 4 columns.

It is like

Column 0 Column 1 Column 2 Column 3
Row 0 a[0][0] a[0][1] a[0][2] a[0][3]
Row 1 a[1][0] a[1][1] a[1][2] a[1][3]

Now let's see how to initialize a 2-dimensional array.

Initialization of 2 D Array


Same as in one-dimensional array, we can assign values to a 2-dimensional array in 2 ways as well.

In the first method, just assign a value to the elements of the array. If no value is assigned to any element, then its value is assigned zero by default.

Suppose we declared a 2-dimensional array a[2][2]. Then to assign it values, we need to assign a value to its elements.

int a[2][2];
a[0][0]=1;
a[0][1]=2;
a[1][0]=3;
a[1][1]=4;

The second way is to declare and assign values at the same time as we did in one-dimensional array.

int a[2][3] = { 1, 2, 3, 4, 5, 6 };

Here, value of a[0][0] is 1, a[0][1] is 2, a[0][2] is 3, a[1][0] is 4, a[1][1] is 5 and a[1][2] is 6.

We can also write the above code as:

int a[2][3] = {
    {1, 2, 3},
    {4, 5, 6 }
};

While assigning values to an array at the time of declaration, there is no need to give dimensions in one-dimensional array, but in 2 D array, we need to give at least the second dimension.

Let's consider different cases of initializing an array.

int a[2][2] = { 1, 2, 3, 4 }; /* valid */
int a[ ][2] = { 1, 2, 3, 4 }; /* valid */
int a[2][ ] = { 1, 2, 3, 4 }; /* invalid */
int a[ ][ ] = { 1, 2, 3, 4 }; /* invalid */

Why use 2 D Array?


Suppose we have 3 students each studying 2 subjects (subject 1 and subject 2) and we have to display the marks in both the subjects of the 3 students. Let's input the marks from the user.

#include <iostream>

using namespace std;

int main(){
	float marks[3][2];
  	int i,j;
  	for( i=0; i<3; i++)
  	{
    	/* input of marks from the user */
    	cout << "Enter marks of student "<< (i+1) << endl;
    	for( j=0; j<2; j++)
    	{
      		cout << "Subject " << (j+1) << endl;
      		cin >> marks[i][j];
    	}
  	}
	 /* printing the marks of students */
  	for( i=0; i<3; i++)
  	{
		cout << "Marks of student " << (i+1) << endl;
    	for( j=0; j<2; j++)
    	{
      		cout << "Subject " << (j+1) << " : " << marks[i][j] << endl;
    	}
  	}
	return 0;
}
Output
Enter marks of student 1
Subject 1
78
Subject 2
94
Enter marks of student 2
Subject 1
87
Subject 2
91
Enter marks of student 3
Subject 1
62
Subject 2
56
Marks of student 1
Subject 1 : 78
Subject 2 : 94
Marks of student 2
Subject 1 : 87
Subject 2 : 91
Marks of student 3
Subject 1 : 62
Subject 2 : 56

In the above example, firstly we defined our array consisting of 3 rows and 2 columns as float marks[3][2];

Here, the elements of the array will contain the marks of the 3 students in the 2 subjects as follows.

Subject 1 Subject 2
Student 1 78 94
Student 2 87 91
Student 3 62 56

In our example, firstly we are taking the value of each element of the array using a for loop inside another for loop.

In the first iteration of the outer for loop, value of 'i' is 0. With the value of 'i' as 0, when the inner for loop first iterates, the value of 'j' becomes zero and thus marks[i][j] becomes marks[0][0]. By writing cin >> marks[i][j];, we are taking the value of marks[0][0].

After that, the inner for loop again iterates and the value of 'j' becomes 1. marks[i][j] becomes marks[0][1] and its value is taken from the user.

Then, the outer loop iterates for the second time and the value of 'i' becomes 1 and the whole process continues.

After assigning the values to the elements of the array, we are printing the values of the elements of the array, in the same way, using another for loop inside for loop.

Let's see one more example of 2 D Array

Suppose there are 2 factories and each of these factories produces items of 4 different types like some items of type 1, some items of type 2 and so on. We have to calculate the total product of each factory i.e. sum of the items of each type that a factory produces.

#include <iostream>

using namespace std;

int main(){
    int s[2][4];
    s[0][0] = 2;
    s[0][1] = 5;
    s[0][2] = 7;
    s[0][3] = 4;
    s[1][0] = 9;
    s[1][1] = 3;
    s[1][2] = 2;
    s[1][3] = 8;
    cout << "Sum of the items produced in the first factory :" << endl;
    int sum1 = 0, sum2 = 0;
    for(int i = 0; i < 4; i++)
    {
        sum1 += s[0][i];
    }
    cout << sum1 << endl;
    cout << "Sum of the items produced in the second factory :" << endl;
    for(int j = 0; j < 4; j++)
    {
        sum2 += s[1][j];
    }
    cout << sum2 << endl;
    return 0;
}
Output
Sum of the items produced in the first factory :
18
Sum of the items produced in the second factory :
22

Here, s[0][i] represents the number of items of the first factory and type i, where i takes value from 0 to 3 using for loop and s[1][i] represents the nunmber of items of the second factory of type i. E.g. - s[0][2] represents the third type of item of first factory and s[1][2] represents the third type of item of second factory. sum1 is the sum of all these items of factory 1. Similar is the case of the second factory.

So, initally, sum1 is 0. Now in first iteration, s[0][i] is s[0][0]. This means that it will represent number of first item of first factory. So, sum1 += s[0][i] will become sum1 += s[0][0]. So, sum1 will become 2. Similarly in second iteration, s[0][i] will become s[0][1] and will represent the second type of items of first factory. Now, sum1 will become 2+5 i.e. 7. Similarly things will go further.

To learn from simple videos, you can always look at our C++ video course on CodesDope Pro. It has over 750 practice questions and over 200 solved examples.

You practice and you get better. It's very simple.
-Phillip Glass

Ask Yours
Post Yours
Doubt? Ask question