Friday, 24 February 2012

Arrays in C


An array is a series of elements of the same type placed in contiguous memory locations that can be individually referenced by adding an index to a unique identifier.

An array is a data structure of multiple elements with the same data type. Array elements are accessed using subscript. The valid range of subscript is 0 to size -1.

Declaration of Array

int arr[10];


Example:


#include
void main(void)
{
int a[5];
int i;
for(i = 0;i<5;i++)
{
a[i]=i;
}

for(i = 0;i<5;i++)
{
printf("%d value of I is = %d\n",i,a[i]);
}
}


Output

1 value of I is = 0

2 value of I is = 1

3 value of I is = 2

4 value of I is = 3

5 value of I is = 4


Multidimensional Arrays
A multi-dimensional array of dimension n (i.e., an n-dimensional array or simply n-D array) is a collection of items which is accessed via n subscript expressions. Multidimensional arrays can be described as "arrays of arrays".
Example:



#include

void main(void){
int a[3][2];
int i,j;
for(i = 0;i<3;i++){
for(j=0;j<2 ;j++) {
scanf(“%d”,&a[i][j]); }
}

for(i = 0;i<3;i++){
for(j=0;j<2;j++) {
printf("value in array %d\n",a[i][j]);
}
}

}

No comments:

Post a Comment