C Array Operations

 

Array Operations

Defining an array

1. Without specifying the size of the array


int arr[] = {1, 2, 3};


Here, we can leave the square brackets empty, although the array cannot be left empty in this case. It must have elements in it.

 

2. With specifying the size of the array


int arr[3];
arr[0] = 1, arr[1] = 2, arr[2] = 3;


Here, we can specify the size of the array in its definition itself. We can then put array elements later as well.

 

Accessing an array element

An element in an array can easily be accessed through its index number. This must be remembered that the index number starts from 0 and not one.


Example:


#include <stdio.h>

int main()

{

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

    printf("%d ", arr[2]); //printing element on index 2

}


Output:

7

 

 

Changing an array element 

An element in an array can be overwritten using its index number.


Example:


#include <stdio.h>

int main()

{

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

    arr[2] = 8; //changing the element on index 2

    printf("%d ", arr[2]); //printing element on index 2

}


Output:

8