You are on page 1of 26

C

Array
Array
 Collection of similar type of data items
 Stored at contiguous memory locations

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


…………….

101-102 103-104 105-106 107-108

 Arrays can store int, char, float, double etc.


 Arrays can store pointer, structure etc.
 Random access
 Less code
Array
 Declaring array
 dataType arrayName[arraySize];
 int array1[6];
 char student[50];
 float balance[25];
 double fraction[10];

array1[0] array1[1] array1[2] array1[3] array1[4] array1[5]

101-102 103-104 105-106 107-108 109-110 111-112

 Size of an array
Array
 Using elements of an array
 Just as simple variables
 array[3]=25;
 array[3]=array[2]+100;
 array[3]=array[0]+array[1];
 printf(“%d”,array[3]);
 scanf(“%d”,&array[3]);
 array[3]=array+25;
 array=array*3;
Array
 
 Initializing array
 dataType arrayName[arraySize]={, ,…, };
Array
 
 Initializing array
 dataType arrayName[arraySize]={, ,…, };
Array
 
 Initializing array
 dataType arrayName[arraySize]={, ,…, };
Array
Array
 Using elements of an array
Array
 Using elements of an array
Array
 Functions with arrays
 return_type function_name(data_type array_name[]) Formal parameter
{
………
}
 function_name(array_name); Actual parameter
Array
 Functions with arrays
Array
 Functions with arrays: Using the size of array
 return_type function_name(data_type array_name[],int size_of_array) Formal parameter
{
………
}
 function_name(array_name,size); Actual parameter
Array
 Functions with arrays
Array
 Functions with elements of array
Array
 Function parameter(s) with elements of array: Call by value
 Function parameter(s) with full array: Call by reference
Array
 Function parameter(s) with full array: Call by reference
 Base address

a[0] a[1] a[2] a[3] a[4]

101-102 103-104 105-106 107-108 109-110

a[0] a[1] a[2] a[3] a[4]


10 20 30 20 10

101-102 103-104 105-106 107-108 109-110


Array
 Function parameter(s) with full array: Call by reference
 Only base address is stored in stack

101
a[0] a[1] a[2] a[3] a[4]
10 20 30 20 10
5
101-102 103-104 105-106 107-108 109-110 return address
Array
 Function parameter(s) with full array: Call by reference
 Calculating address of other elements using base address
address of element [i]=base address+(i*scale factor of data type) a[0] a[1] a[2] a[3] a[4]
address of a[3]=101+(3*2) 10 20 30 20 10
address of a[3]=107 101-102 103-104 105-106 107-108 109-110
Array
2D Array
 dataType arrayName[rowSize][columnSize];
 int a[2][3];

a[0][0] a[0][1] a[0][2]


a[1][0] a[1][1] a[1][2]

a[0][0] a[0][1] a[0][2] a[1][0] a[1][1] a[1][2]


1017-1018 1019-1020
2D Array
 Initializing 2D array
 int a[2][3]={5,7,6,9,2,4};
 int a[2][3]={{5,7,6},{9,2,4}};
 int a[2][3]={
{5,7,6},
{9,2,4}
};
2D Array
2D Array
 Functions and 2D arrays

You might also like