Home >>C++ Tutorial >C++ Arrays

C++ Arrays

C++ Arrays

The group of similar types of elements that have a contiguous memory location is known to be an array in C++. It is basically similar to the arrays available in all other programming languages.

In order to encapsulates the fixed size arrays, std:array is used in the C++ that is basically a container. Please note that the programmers can only store the fixed set of elements in the C++ array and the indexing starts from 0.

Advantages of Arrays in C++

  • Code Optimization i.e. code writing is less.
  • Can be accessed randomly.
  • Its easy to traverse the data
  • Data can be manipulated easily.
  • Data can be sorted easily.

Disadvantages of Arrays in C++

There is only one disadvantage that it is of fixed size.

Arrays types in C++

There are generally two types of arrays in C++:

  • Single Dimensional Array
  • Multidimensional Array

1. Single Dimensional Array in C++

These are the group of elements that have same datatype and the same name. Here is an example that will elaborate the concept of these arrays:

Example of Single Dimensional Array

#include <iostream>  
using namespace std;  
int main()  
{  
	int arr[4]={10,11,12,13};       
	for (int i = 0; i < 4; i++)    
	{    
		cout<<arr[i]<<" ";    
	}    
}  
Outptu
10 11 12 13

Another Example of Single Dimensional Array(Sum of given array)

#include <iostream>  
using namespace std;  
int main()  
{  
	int sum=0;
	int arr[4]={10,11,12,13};       
	for (int i = 0; i < 4; i++)    
	{    
	sum=sum+arr[i];   
	}
	cout<<"Sum of array="<<sum; 	
}  
Outptu
Sum of array=46

Another Example of Single Dimensional Array(Sum of even and odd of given array)

#include <iostream>  
using namespace std;  
int main()  
{  
	int even=0;
	int odd=0;
	int arr[4]={10,11,12,13};       
	for (int i = 0; i < 4; i++)    
	{    
		if(arr[i]%2==0)
		{
		even=even+arr[i];   
		}
		else
		{
		odd=odd+arr[i];
		}
	}
	cout<<"Sum of even="<<even<<"\n";
	cout<<"Sum of odd="<<odd; 	
}  
Outptu
Sum of even=22
Sum of odd=24

2. Multi-Dimensional Array in C++

These arrays can be of two or three dimensional and also known as the rectangular arrays as the data is stored in them in the form of matrix. This array returns the element sequentially.

Here is an example that will make your concept clear about this type of array:

#include <iostream>  
using namespace std;  
int main()  
{  
    int arr[2][2];  //declaration of array   
    arr[0][0]=10;  //initialization  of array  
    arr[0][1]=11;   
    arr[1][0]=12;  
    arr[1][1]=13;  
    for(int i = 0; i < 2; ++i)  
    {  
        for(int j = 0; j < 2; ++j)  
        {  
            cout<< arr[i][j]<<" ";  
        }  
        cout<<"\n";    
    }  
    return 0;  
}  
Output :
10 11
12 13