Array in C

0 earthaw36621147 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.

One Dimensional Array
One Dimensional Array

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 <stdio.h>

int main(){

    int arr[] = {5, 7, 9, 11, 13};
   printf("First Element is %d", arr[0]);
    printf( "Second Element is %d", arr[1] );    printf("Third Element is %d", arr[2]);    printf("Fourth Element is %d", arr[3]);    printf("Fifth Element is %d", arr[4]);
    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 <stdio.h>

int main(){

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

    for(i=0; i < 5; i++)
        printf("Element with index %d", arr[i]);;

    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