C Programming language-C Arrays

C Arrays

An array in C stores the fixed-sized sequential collection of elements of the same data type. For instance, if you want to store ten numbers of the same data type, you can store it in an array instead of storing it in ten different variables. An array type can be any valid C data types. The size of the array should be an integer constant greater than zero.

There are three types of arrays in C programming, such as

  • One-Dimensional array
  • Two-Dimensional array
  • Multi-Dimensional array

Array Definition in C

The following is the syntax for array definition in C

Syntax:

type arrayName[size];

The type can be any C data type. The arrayName is the name of the array. The size must be an integer constant greater than zero.

Example:

int numbers[10];

Array Initialization in C

Arrays can be initialized in two ways. Firstly, the arrays are initialized while declaring it.

Example:

int number[5] = {10, 20, 30, 40, 50};
Secondly, the arrays can be initialized with each element separately in a loop. 

Example:

int newArray[5];

    //Initializing the array newArray
    for (int i=0; i<sizeof(newArray); i++)
    {
        newArray[i] = i+1;
    }
In the above example, we assign the value to the array element with the index value i+1 for each element.

Pictorial Representation of C Array


newArray12345

01234
Accessing array elements 

The array elements in C can be accessed with its index value. The following example will explain how to access the array elements.

Example:
#include<stdio.h>

int main()
{
    int newArray[5];

    //Initializing the array newArray
    for (int i=0; i<sizeof(newArray); i++)
    {
        newArray[i] = i+1;
    }

    printf("The third element is %d\n", newArray[2]);
}
Output:
The third element is 3