C++ Array
An
array is a collection of data (elements) of the same data types. The elements of an array are allocated in contiguous memory allocation. Elements of the array are accessed through the index
(indices) of that element.
Types of array
- Single dimension array
- Two dimension array
- Multi-dimension array
Declaration of Array
data_type array_Name[size];
In the above declaration, data_type is C++ data type, array_Name is the name of array and size is the total size of elements.
Initialization of Array
An array is initialized with data type followed by an array name and the total size of elements. Here, elements are assigned into an array.
int mark[5] = { 80,75,85,60,90};
Another way to initialize array is as follow:
int mark[] = { 80,75,85,60,90};
Access of Array
Elements of the array are accessed through the index
(indices) of that element. The index of an array is started from
0 and end at
size-1 of array.
CPP Access of Array
Suppose we want to access the individual elements of an array, this can be done by the passing index of the element in array name.
mark[0]=80;
mark[1]=75;
mark[2]=85;
mark[3]=60;
mark[4]=90;
Single dimension array Example
Printing the elements of an array using 'for' loop.
#include <iostream>
using namespace std;
int main()
{
int mark[5]={80,75,85,60,90},i;
for (int i = 0; i < 5; ++i)
{
cout<< mark[i]<<endl;
}
return 0;
}
Output: