# Programs

## C Accessing array

In the previous chapters we have already learnt about the basic concepts of array and how to create and initialize array. In this chapter we will be learning how we will be accessing array.

## C Programming : Accessing Array

1. We all know that array elements are randomly accessed using the subscript variable.
2. Array can be accessed using array-name and subscript variable written inside pair of square brackets [].

Consider the below example of an array – In this example we will be accessing array like this –

```arr  = Third Element of Array
arr  = Fifth Element of Array
arr  = Eighth Element of Array```

whereas elements are assigned to an array using below way –

```arr  = 51
arr  = 32
arr  = 43
arr  = 24
arr  = 5
arr  = 26```

### Program #1 : Accessing array

```#include<stdio.h>
#include<conio.h>

void main()
{
int arr[] = {51,32,43,24,5,26};
int i;
for(i=0; i<=5; i++) {
printf("\nElement at arr[%d] is %d",i,arr[i]);
}
getch();
}
```

Output :

```Element at arr is 51
Element at arr is 32
Element at arr is 43
Element at arr is 24
Element at arr is 5
Element at arr is 26
```

## How a[i] Works ?

We have following array which is declared like this –

`int arr[] = { 51,32,43,24,5,26};`

As we have elements in an array, so we have track of base address of an array. Below things are important to access an array –

Expression Description Example
arr It returns the base address of an array Consider 2000
*arr It gives zeroth element of an array 51
*(arr+0) It also gives zeroth element of an array 51
*(arr+1) It gives first element of an array 32

So whenever we tried accessing array using arr[i] then it returns an element at the location `*(arr + i)`

Accessing array a[i] means retrieving element from address (a + i).

We have listed out some of our observations and conclusions

```arr[i]    = 5
*(arr+i)  = 5
*(i+arr)  = 5
i[arr]    = 5```

all of the above notations yields same result. lets prove it using below program –

### Program #2 : Accessing array

```#include<stdio.h>
#include<conio.h>

void main()
{
int arr[] = {51,32,43,24,5,26};
int i;
for(i=0; i<=5; i++) {
printf("\n%d %d %d %d",arr[i],*(i+arr),*(arr+i),i[arr]);
}
getch();
}
```

Output :

```51 51 51 51
32 32 32 32
43 43 43 43
24 24 24 24
5 5 5 5
26 26 26 26```