Array Declaration

What is an array?

An array is a sequenced collection of elements of the same data type. All the elements in an array have same size and data type. It is used to store large volume of similar data. For example:-

  • Salaries of employees in an organisation.
  • Marks of students obtained in an examination

A single dimensional array (more on this later) is simply declared like shown below:-

int salary[15]; 

where 'salary' is an array of integer data type which contains 15 elements.

SYNTAX

data type array_name[index];

"index" represents the total numbof elements in the array.

Types of Arrays:-

  •  One Dimensional Arrays
  • Two Dimensional Arrays
  • Multi Dimensonal Arrays

 

ONE DIMENSIONAL ARRAYS

In a One Dimensional array we have a single index i.e. the array consists of only a single subscript.

Example:-

a[0],a[1],a[2],a[3],...........a[n-1]

It can be observed that total number of elements in above array is 'n'.

  • In C Programming language, an array is initialised from zeroth element to (n-1)th element.
  • But total number of elements will be 'n'.

An array can be declared in the following ways:-

  • int num[]={2,8,7,6,0};

C array example

Here we dont need to mention the size of the integer array since we are assigning the values to all the elements at the time of the declaration itself.

  • char a[3];
  • a[0]='A';
  • a[1]='B';
  • a[2]='C';

Here we have declared an array of character type by mentioning its size only at declration time and we have assigned the values later on.

 

 

Complete Source Code

 

#include <stdio.h>
#include <conio.h>
void main()
{
 int a[5];
 clrscr();
 a[0]=120;
 a[1]=32;
 a[2]=64;
 a[3]=9;
 a[4]=170;
 printf("Value of 1st element, a[0] is %d \n",a[0]);
 printf("Value of 2nd element, a[1] is %d \n",a[1]);
 printf("Value of 3rd element, a[2] is %d \n",a[2]);
 printf("Value of 4th element, a[3] is %d \n",a[3]);
 printf("Value of 5th element, a[4] is %d \n",a[4]);
 getch();

}

 

Output of the program is shown below:

 

Ouput - C array 1 D program

 

Download source code.