What is Array in C

It is a collection of similar types of data elements in a single entity.
When we require 'n' number of values of the same data type, then recommended creating an array.

Syntax:

Data type arr [number of elements]

Example: Suppose you wish to store multiple values of 50 integers, you can create an array for it.

int data[50];

An array can be described as the group of similar data types stored at contiguous memory locations. They are the derived data type that can store the primitive data type like int, char, float, etc.

 

Properties of Array

The array includes the following properties.

  • All data items in an array must be of the same data type.
  • Data items of an array are stored at contiguous memory locations.
  • Data items in an array can be accessed randomly with help of indexes though we can estimate the address of every element in an array with the given base address and the size of the data item.
  • Always array index must be required to start with '0' and end with (size -1).
  • In the declaration of an array, the size must be an unsigned integer constant whose value is greater than 0 only.

 

Initialisation of an Array

Initialise the array with fixed number of elements like below.
int arr[3] = {10,20,30}

Specifying the size of the array is an option during the Initialisation, in this case, compiler automatically understands the number of elements in the array.
int arr[]={10,20,30}

You cannot Initialise an array with more than the number of elements specified in the array.
int arr[3]= {10,20,30,40} --> this will give error.

 

Accessing the Array Elements

You can access the array element using the index number and it starts with 0 to (size -1).

 int arr[3]={10,20,30};
int arr[0]=10;  --> At index 0 , value is 10.
int arr[1]=20; --> At index 1 , value is 20.
int arr[3]=30; --> At index 2 , value is 30.

You can modify the array elements value like below.

 int data[5]={10,20,30,40,50}; --> Now change the array 3rd element value to 25
int data[2]=25;
now new array will be look like this --> data[5]={10,20,25,40,50};

 

Simple Array Program

In this program, we declare a array and provide the value to the array and after we will read the value through the index number

#include<stdio.h>
int main(){
  int data[4];

  printf("Enter the 4 integers value:\n");

  // Storing the input value to array using index number
  for(int i = 0; i < 4; ++i) {
     scanf("%d", &data[i]);
  }

  // Reading the array value 
  for(int i = 0; i < 4; ++i) {
     printf("Array value at index number%d = %d\n", i,data[i]);
  }
  return 0;
}

Output

 

Some Common Mistakes of Array Declaration

In the declaration of an array, size cannot be variable or constant variable.

Example:

int size=10;
int arr[size];  // this is not valid and it gives the error
const int size=10;
int data[size]; // invalid and it gives the error