Vous êtes sur la page 1sur 3

ARRAY What is an Array? An array is a collection of same type of elements which are sheltered under a common name.

An array is defined as following (The general form) : data_type array_name[no.of array elements]; data type - the type of elements that an array stores. array name - the name that is given to array. [number of elements] -This value in subscripts [] indicates the number of elements the array stores. Accessing Data in Array A program may use the current value stored in arrays elements just as it would use any variable. In any point of a program in which an array is visible, we can access the value of any of its elements individually as if it was a normal variable. The General format is given below name[index]=assigned value Ex: an array has 5 elements array[5] ; array[0]=2; array[1]=4; array[2]=8; array[3]=16; array[4]=32 Passing Arrays and Array Elements to Functions You can pass an entire array to a function or pass single array element to a function, the array name is the address of the first element (name[0]) of the array. Here is a typical prototype of passing a one-dimensional array to a function: Ex : void PassElement(char Name[MAX]); To call this function and pass the array, use the statement, PassElement(Name) You can pass to the function a pointer to an array by specifying the array's name without an index. Another Example : void myfunction(char name[max]); myfunction(name)

Multi-Dimensional Array A multi-dimensional array is a simply an extension of one-dimensional array. The most common multidimensional array is the two dimensional array.

Defining a Multi-dimensional Array To define a two-dimensional array is almost the same as you define a one-dimensional array. Syntax: Data_type array_name [number of rows][number of columns]; EX: Int Month [ day][week] where const int week=4; and const int day=7 Initializing Multi-Dimensional Array Multi-dimensional array can be pre-initialized in a similar manner to single dimensional array. data_type array_name[n][m]= { {1,4,5,8,9} {2,4,6,8,10} {1,3,5,7,9} } Example: int x[3][4]= {{0,1,2,3},{4,5,6,7},{8,9,10,11}} It is equivalent to: int x[3][4] = {0,1,2,3,4,5,6,7,8,9,10,11}; Assigning Value to an Array The elements of an array can be assigned value Array_name[n][m]=element value;

just like any variable

Example: Tax[5][10] Comm[4][5][1]=65; Accessing Data in Array We could access the element at the intersection of the nth row and mth column using two array operators with the following expression. variable_object_identifier=array_name[name][n][m]; Ex. x= Sales report[2][3]; y= Temperature[4][San Diego]; EXAMPLE PROGRAM #include<stdio.h> #include<conio.h> main() { char age[4]; age[0]=12; age[1]=34; age[2]=56; age[3]=78; printf{%d\n,age[0]); printf{%d\n,age[1]); printf{%d\n,age[2]); printf{%d\n,age[3]); getch(); return 0; }