Array

0 qfzernestine298 November 13, 2020

An array is a group of related data items that share a common name. In the other words, an array is a data structure that stores a number of data items as a single entity (object). The individual data items are called elements and all of them have some data types. An array is used when multiple data items that have common characteristics are required.

Declaration of a 1-D array

There are many ways to declare a one-dimensional array.

A. Method 1:

``````int arr[3];
arr[0] = 5;
arr[1] = 7;
arr[2] = 2;``````

B. Method 2:

``int arr[3] = {5, 7, 2};``

C. Method 3:

``int arr[] = {5, 7, 2};``

Accessing array elements

We must know that the array index starts at 0, which means the first element is at index 0 and the second element is at index 1, and so on.

Let’s take one example using the above concepts to make clear concepts on accessing array elements.

``````#include <iostream>
using namespace std;

int main(){

int arr[] = {5, 7, 9, 11, 13};
cout << "First Element is " << arr[0] << endl;
cout << "Second Element is " << arr[1] << endl;
cout << "Third Element is " << arr[2] << endl;
cout << "Fourth Element is " << arr[3] << endl;
cout << "Fifth Element is " << arr[4] << endl;

return 0;
}``````

The output of the above program is:

``````First Element is 5
Second Element is 7
Third Element is 9
Fourth Element is 11
Fifth Element is 13``````

Although this method works for accessing array elements but this method is not recommended to access all the elements. For accessing a single element, this method works fine, or if you want to display all elements, use a loop to display all elements.

``````#include <iostream>
using namespace std;

int main(){

int arr[] = {5, 7, 9, 11, 13};
int i = 0;

for(i=0; i < 5; i++)
cout << "Element with index " << i << " is " << arr[i] << endl;

return 0;
}``````

The output of the above program is:

``````Element with index 0 is 5
Element with index 1 is 7
Element with index 2 is 9
Element with index 3 is 11
Element with index 4 is 13``````