Home >>C++ Tutorial >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.
There is only one disadvantage that it is of fixed size.
There are generally two types of arrays 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]<<" "; } }
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; }
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; }
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; }