How to access an array element in C language?

CServer Side ProgrammingProgramming

An array is a group of related data items that share a common name. A particular value in an array is identified by using its "index number" or "subscript".

The advantage of an array is as follows −

  • The ability to use a single name to represent a collection of items and to refer to an item by specifying the item number enables the user to develop concise and efficient programs.

The syntax for declaring array is as follows −

datatype array_name [size];

For example,

float height [50]

This declares ‘height’ to be an array containing 50 float elements.

int group[10]

This declares the ‘group’ as an array to contain a maximum of 10 integer constants.

Individual elements are identified using "array subscripts". While complete set of values are referred to as an array, individual values are called "elements".

Accessing the array elements is easy by using an array index.

Example

Following is the C program for accessing an array −

 Live Demo

#include<stdio.h>
int main(){
   int array[5],i ;
   array[3]=12;
   array[1]=35;
   array[0]=46;
   printf("Array elements are: ");
   for(i=0;i<5;i++){
      printf("%d ",array[i]);
   }
   return 0;
}

Output

When the above program is executed, it produces the following result −

Array elements are: 46 35 38 12 9704368
Array[2] and array[4] prints garbage values because we didn’t enter any values in that locations
raja
Published on 08-Mar-2021 10:02:11
Advertisements