Chapter no. 3 Arrays and Strings
Array Array is a data structure that represents a collection of the same types of data.
data-type var-name[num-of-elements]; e.g.
float alpha[6]; int num[10];
num
num[0] num[1] num[2] num[3] num[4] num[5] num[6] num[7] num[8] num[9]
num[0] - references the first element in the array. num[9] - references the last element in the array. -1-
By, Kute T. B. for CPR (FYIF) 2007-08
Chapter no. 3 Arrays and Strings
Declaring and Creating in One Step datatype arrayname[arraySize]= {values seperated by comma}; Example : char ch[5] = {‘a’, ’ ‘F’, ‘4’, ‘=’,‘n’ }; int i[4] = {12, 15, 0, 2}; float x[3] = {52.3, 88.0, 11.2}; x[0] x[1] x[2]
52.3 88.0 11.2
int s[10] = {8, 25, 45, 102}; s[4] to s[9] will be initialized to 0 automatically. int arr[10] = { 0 }; initializes the whole array with 0 value. -2-
By, Kute T. B. for CPR (FYIF) 2007-08
Chapter no. 3 Arrays and Strings
Run time initialization of arrays int i, rate[10]; for(i=0;i<10;i++) { printf(“\nEnter number : ”); scanf(“%d”, &rate[i]); } printf(“\n Numbers are : ”); for(i=0;i<10;i++) { printf(“\n %d”, rate[i]); } ---------------------------------------Copying arrays int array1[5] = {2, 3, 1, 5, 10}; int array2[5]; array2 = array1;
-3-
By, Kute T. B. for CPR (FYIF) 2007-08
Chapter no. 3 Arrays and Strings
Two dimensional Array Declaration: data-type array-name[rows][cols]; e.g. int matrix[4][5]; 0 rows
columns 1 2 3
4
0 1 2 3
matrix[3][0]
matrix[2][3]
-4-
By, Kute T. B. for CPR (FYIF) 2007-08
Chapter no. 3 Arrays and Strings
Compile time initialization of 2-D array int arr[5][5] = { {5,8,9,6,8}, {6,4,1,2,3}, {0,0,1,7,3}, {4,7,8,8,8}, {0,7,3,1,4} }; Or int arr[5][5] = { 5,8,9,6,8, 6,4,1,2,3, 0,0,1,7,3, 4,7,8,8,8, 0,7,3,1,4 }; 5 6 0 4 0
8 4 0 7 7
-5-
9 1 1 8 3
6 2 7 8 1
8 3 3 8 4
By, Kute T. B. for CPR (FYIF) 2007-08