Introduction to Array in C | One dimensional array in C

Preview
You must first complete for statement in c language | Nesting of for in c language before viewing this Lesson

Introduction to Array in C

Array is a collection of values having same data type and size. Values in array are internally stored in consecutive locations. Elements of an  array can be processed by using index positions of elements where  index starts from 0 that means first array element is at at index 0.

There are three types of array:

  • One dimensional Array
  • Two dimensional Array
  • Multi dimensional Array



One dimensional Array

In one dimensional array, we use only one subscript to specify the size or refer any array element. Syntax for declaring an array is:

<Type> Array_name[N];

Type represents valid data type of C like int, float, char etc.
Array_name is the array name defined by the programmer.
[ ] are called subscript used to define  array size within them.
is the size of array.

Example

int ARR[4];

Here A is a one dimensional array which can store maximum 4 values in it. Elements of array are referred as ARR[0],ARR[1],ARR[2] and ARR[3].

Program 
#include<stdio.h>
int main()
{
int ARR[3];
ARR[0]=10;
ARR[1]=20;
ARR[2]=30;
printf(“\n%d”,ARR[0]);
printf(“\n%d”,ARR[1]);
printf(“\n%d”,ARR[2]);
return(0);
}
Output
10
20
30



Initialization of  one dimensional Array in C

Syntax to initialize a one dimensional array is:

<Type> Array_name[N]={List_of_values};

N specifies the size of array. It is optional while initializing array. Compiler automatically provides size to array as per number of values within the braces if we don’t specify array size during initialization.

Example

int a[3]={15,25,35};  //Initialization of int type array

Program for initialization of one dimensional array.
#include<stdio.h>
int main()
{
int i, arr[4]={10,20,30,40};
printf(“\nArray is”);
for(i=0;i<4;i++)
printf(“\n%d”,arr[i]);
return(0);
}
Output
Array is
10
20
30
40



Program to read and display  one dimensional array.
#include<stdio.h>
int main()
{
int arr[4];
int i;
printf(“\nEnter array elements :=”);
for(i=0;i<4;i++)
scanf(“%d”,&arr[i]);printf(“\nArray elements are:=”);
for(i=0;i<4;i++)
printf(“\n%d”,arr[i]);
return(0);
}
Output
Enter array elements :=3
4
5
6
Array elements are:=
3
4
5
6



 

Best Books of C





Lesson tags: initialization of one dimensional array in c, one dimensional array in c, reading one dimensional array in c, types of array in c
Back to: C Programming Language