510 likes | 635 Views
EKT120 COMPUTER PROGRAMMING. Arrays (Part I) Dr. Nik Adilah Hanin Bt. Zahri adilahhanin@unimap.edu.my. Outline. Introduction to Array Arrays of Data Array Declaration Array Initialization Operations on Array Multidimensional Arrays Index out of bound Passing Arrays to Function
E N D
EKT120COMPUTER PROGRAMMING Arrays (Part I) Dr. NikAdilahHanin Bt. Zahri adilahhanin@unimap.edu.my
Outline • Introduction to Array • Arrays of Data • Array Declaration • Array Initialization • Operations on Array • Multidimensional Arrays • Index out of bound • Passing Arrays to Function • Displaying Array in a Function • How Arrays are passed in a function call
What is Array? • The variables that we have used so far have all common characteristics: • Each variable could only store a single value at a time. • Example: intiCount, iLength, iNum; double dAverage, dTotal; char cSelection, cChoice; • An array is a collection of a fixed number of components wherein all of the components are of the same type
What is Array? (Example) • Example: Suppose that there is a list of five integers: 5, 10, 15, 20, and 25 • Previously we would declare five variables: int iNum1,iNum2,iNum3,iNum4,iNum5; • By using array, since they are all of the same data type, we could just write: intaiNum[5];
What is Array? (Example) aiNum • intaiNum[5]; • 5 components or elements in this array • Elements are referred to index • Element aiNum[2] has index 2 and value 15 aiNum[0] aiNum[1] aiNum[2] aiNum[3] aiNum[4]
Arrays of Data • Engineering applications usually involve large chunk of data (of common type) • Arrays provide easy and efficient concept for data storage or management • Arrays are usually processed through loops • Arrays are accessed by indicating an address or index
Arrays in C • Arrays can assume any type (including the primitive data types) int, char, double, float, etc. • Like any other instances, arrays must be declared before use.
Array Declaration Format: data_typearray_name[int value]; Example: • intaiList[5]; • const intMax_List_Size = 10; intaiHours[Max_List_Size]; • const int SIZE = 100; double adAmount[SIZE]; • const intMax_List_Size = 6; char acAlphas[Max_List_Size]; • #define N 10 double adB[N];
Multiple Instances vs. Array // multiple instance int iValue1, iValue2, iValue3; printf(“Enter value 1: “); scanf (“%d”, &iValue1); printf(“Enter value 2: “); scanf(“%d”, &iValue2); printf (“Enter value 3: “); scanf(“%d”, &iValue3); // process or display // array intaiValue[3]; intiCount; for(iCount=0;iCount<3;iCount++) { printf(“Enter value %d :”,iCount); scanf(“%d”,&aiValue[iCount]); } // process or display
Arrays - Memory Allocation • Arrays are allocated bulk memory • Single reference used for multiple locations • Items are accessed based on index (address) with reference to first item index aiValue 0 1 2 3 4 5 6 7 intaiValue[8]; aiValue[0]=23; aiValue[1]=56; aiValue[2]=100; aiValue[3]=0; aiValue[4]=12; aiValue[5]=234; aiValue[6]=666; aiValue[7]=4;
Arrays Arithmetic • Operations on arrays are similar to basic variables. • Example: • iSum = aiNum[0] + aiNum[1] + aiNum[2]; • iMultiply = 3 * aiNum[1]; • iRemainder = aiNum[3] % 3; • iTotal = aiNum[1] * aiNum[2];
Array Initialization during Declaration • Arrays can be initialized directly, but assignments are done using loops • Like any other simple variable, arrays can also be initialized while they are being declared. • Example: double adSales[5] = {12.25, 32.50, 16.90, 23,45.68}; adSales[0]=12.25, adSales[1]=32.50, adSales[2]=16.90, adSales[3]=23.00, adSales[4]=45.68;
Array Initialization during Declaration (cont…) • Initializers: • If not enough initializes, rightmost element becomes 0 intaiN[7] = { 1, 2, 3, 4, 5 }; => aiN[5] = aiN[6] = 0 • All elements = 0 intaiN[5] = {0} ; • If size is omitted, initializers determine the size intaiN[ ] = { 1, 2, 3, 4, 5 }; 5 initializers, therefore 5 element array
Array Initialization during Declaration (cont…) • When declaring and initializing arrays, it is not necessary to specify the size of the array. • The size of the array is determined by the number of initial values in the braces. double adSales[]={12.25,32.50, 16.90,45.68};
Sample Program 1 Initializes the first 2 elements of the aiA[]array. All the other elements are then automatically set to zero #include <stdio.h> int main() { intaiA[3]= {11,22}, aiB[]={44, 55, 66}; printf(“aiA[0]=%2d, aiA[1]=%2d, aiA[2]=%2d \n “aiB[0]=%2d, aiB[1]=%2d, aiB[2]=%2d \n\n", aiA[0],aiA[1],aiA[2],aiB[0],aiB[1],aiB[2]); return 0; } Because no array size is given (the brackets are empty) and three values are given in braces, the array is automatically declared to have a size of 3 with the value shown being the initial element values.
Sample Program 1 Initializes the first 2 elements of the aiA[]array. All the other elements are then automatically set to zero #include <stdio.h> int main() { intaiA[3]= {11,22}, aiB[]={44, 55, 66}; printf(“aiA[0]=%2d, aiA[1]=%2d, aiA[2]=%2d \n “aiB[0]=%2d, aiB[1]=%2d, aiB[2]=%2d \n\n", aiA[0],aiA[1],aiA[2],aiB[0],aiB[1],aiB[2]); return 0; } Because no array size is given (the brackets are empty) and three values are given in braces, the array is automatically declared to have a size of 3 with the value shown being the initial element values. Output: aiA[0]=11, aiA[1]=22, aiA[2]= 0 aiB[0]=44, aiB[1]=55, aiB[2]=66
Sample Program 2 #include <stdio.h> int main() { intlistA[2],listB[5],iLoop; printf("Please enter two integers\n"); scanf("%d %d",&listA[0], &listA[1]); printf(“\n listA[0] = %d listA[1] = %d\n\n", listA[0], listA[1]); printf("Please enter five integers\n"); for(iLoop=0;iLoop<5;iLoop++) scanf("%d",&listB[iLoop]); for(iLoop=0;iLoop<5;iLoop++) printf(“listB[iLoop]=%d ",listB[iLoop]); printf(”\n”); return 0; }
Sample Program 2 #include <stdio.h> int main() { intlistA[2],listB[5],iLoop; printf("Please enter two integers\n"); scanf("%d %d",&listA[0], &listB[1]); printf(“\n listA[0] = %d listA[1] = %d\n\n", listA[0], listA[1]); printf("Please enter five integers\n"); for(iLoop=0;iLoop<5;iLoop++) scanf("%d",&listB[iLoop]); for(iLoop=0;iLoop<5;iLoop++) printf(“listB[iLoop]=%d ",listB[iLoop]); printf(”\n”); return 0; } Output: Please enter two integer 2 listA[0] = 1 listA[1] = 2 Please enter five integers 3 4 5 6 7 listB[0]= 3 listB[1]= 4 listB[2]= 5 listB[3]= 6 listB[4]=7
Sample Program 3 All elements are set to 0. #include <stdio.h> #define n 5 int main() { int list[n]={0},iLoop; for (iLoop=0;iLoop<5;iLoop++) { list[iLoop]= iLoop*100.0; printf(“list[%d]=%d\n", iLoop, list[iLoop]); } return 0; } Using a loop to fill all the elements of the list[] array. 19
Sample Program 3 All elements are set to 0. #include <stdio.h> #define n 5 int main() { int list[5]={0},iLoop; for (iLoop=0;iLoop<5;iLoop++) { list[iLoop]= iLoop*100.0; printf(“list[%d]=%d\n", iLoop, list[iLoop]); } return 0; } Using a loop to fill all the elements of the list[] array. Output: list[0]=0 list[1]=100 list[2]=200 list[3]=300 list[4]=400 20
Sample Program 4 #include<stdio.h> #define n 10 //define number of n in the array void main() { intiLoop, iTotal = 0; //variable declaration intaiY[n]={9,6,20,5,12}; //array declaration & //initialization for (iLoop=0;iLoop<n;iLoop++) iTotal = iTotal + aiY[iLoop]; printf ("\nTotal = %d\n”, iTotal); } • the array size n is declared in the define statement.
Sample Program 4 #include<stdio.h> #define n 10 //define number of n in the array void main() { intiLoop, iTotal = 0; //variable declaration intaiY[n]={9,6,20,5,12}; //array declaration & //initialization for (iLoop=0;iLoop<n;iLoop++) iTotal = iTotal + aiY[iLoop]; printf ("\nTotal = %d\n”, iTotal); } • program declares and initializes the array aiY
Sample Program 4 #include<stdio.h> #define n 10 //define number of n in the array void main() { intiLoop, iTotal = 0; intaiY[n]={9,6,20,5,12}; for (iLoop=0;iLoop<n;iLoop++) iTotal = iTotal + aiY[iLoop]; printf ("\nTotal = %d\n”, iTotal); } • For each loop iteration, the value accessed id is added to the variable iTotal which is finally displayed.
Notes • The defined constants, #define is used to ease any future amendments of the codes, for instance, if the array is to be widen to an n of 10 instead of 5, it would be adequate by modifying the line: #define n 5 #define n 10 there is no need to make any other changes to the program, thus making the life of programmer easier.
Operations on Array • Storing/Reading data in an array for (iIndex = 0; iIndex < 10; iIndex++) scanf (“%d”, &aiSale[iIndex]); • Printing an array for (iIndex = 0; iIndex < 10; iIndex++) printf (“%d ”, aiSale[iIndex]);
Parallel Arrays • Two (or more) arrays are called parallelif their corresponding components hold related information. intaiStudentId[50]; char acStudentGrade[50];
Multi-Dimensional Arrays • Arrays can have multiple dimensions • Most used is the 2-dimensional array (for matrix implementation) • Actual implementation is a single array (segmented) • Nested loopstructure usually used to access items
Example : 2-Dimensional Array intaiValue[4][2]; aiValue[2][1]=5; Column 0 1 0 1 2 3 Row
Example : 2-Dimensional Array intaiValue[4][2]; aiValue[2][1]=5; Column 0 1 0 1 2 3 Row
Multi-Dimensional Arrays (cont..) • A collection of the same type of data stored in contiguous and increasing memory locations. • Declaration of multi-dimensional array: intaiB[2][3] = {51, 52, 53, 54, 55, 56}; array_type array_name array dimension = 2 two rows three columns first row initial values second row initial values
Multi-Dimensional Arrays (cont..) • Multi-dimensional array can be initialized directly in the declaration statement. • For example: • intaiB[2][3] = {51,52,53,54,55,56}; which initializes the elements to be aiB[0][0]=51 aiB[0][1]=52 aiB[0][2]=53 aiB[1][0]=54 aiB[1][1]=55 aiB[1][2]=56 • note that C begins its subscripts at 0. • The rightmost subscript is incremented first.
Multi-Dimensional Arrays (cont..) • can use braces ({ }) to separate rows in 2-dimensional arrays • For example: • intaiC [4][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}, {10,11,12}}; 3 columns 4 rows rows columns
Multi-Dimensional Arrays (cont..) • For example: • intaiC [4][3] = { {1, 2}, {4, 5, 6}, {7}, {10,11,12} }; initializes aiC[0][2], aiC[2][1] and aiC[2][2] to be 0 • intaiC [ ][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}, {10,11,12}}; implicitly declares the number of rows to be 4
Notes on Arrays • Arrays enable better and easier data management system • Closely related to loops • Indexing is zero-based (0 to n-1 for an array with n locations) • Multi-dimensional arrays require nested loopstructure (e.g. 2-dimensional array)
Index out of bounds • ‘Out of bounds’ is when (index < 0) or (index > arraySize - 1) • It is a run-time error, happens when an index is outside the valid boundaries of the array. Example: intaiA[10]; intiX = 10 aiA[9]=3; //ok aiA[iX]=4;//10 is not within the range 0..9 • In C, no guard against this problem • Does not check whether index value is within range or not • Can result in accessing data of wrong memory location
How to overcome? • Use defined loops for (iLoop=0; iLoop<10; iLoop++) aiList[iLoop] = 0;
Passing Arrays to Function void fnInitialize(intaiList[]) { intiCount; for(iCount=0; iCount<5; iCount++) aiList[iCount] = 0; } • Initializesintarray of size 5 to 0.
Array as Parameter in Function • If size changes (lets say 10 or 20), need to write another function. not practical and inflexible. • Therefore, introduce another variable, iSize. void fnInitialize(intaiList[], intiSize) { intiCount; for(iCount=0; iCount<iSize; iCount++) aiList[iCount] = 0; }
Constant Arrays • Prevent the function from changing the values in array. • Use word const in declaration. • Function can modify array aiX but not array aiY. void fnExample(intaiX[], const intaiY[], intiSizeX[],intiSizeY[]) { ... ... ... }
Initializing Array to 0 void fnInitializeArray (intaiX[],intiSizeX) { intiCounter; for(iCounter=0; iCounter<iSizeX; iCounter++) aiX [iCounter] = 0; }
Reading and Storing Data in Array void fnFillArray(intaiX[ ],intiSizeX) { intiCounter; for(iCounter=0;iCounter<iSizeX;iCounter++) scanf (“%d”, &aiX[iCounter]); }
Displaying Array in a Function void fnPrintArray(const intaiX[],intiSizeX) { intiCounter; for(iCounter=0;iCounter<iSizeX;iCounter ++) printf (“%d”, aiX [iCounter]); }
Finding and Returning Value of Array intfnSumArray(const intaiX[], intiSizeX) { intiCounter; intiSum = 0; for(iCounter=0;iCounter<iSizeX;iCounter++) iSum = iSum + aiX[iCounter]; return (iSum); }
Finding and Returning Index of Largest Element of an Array intfnIndexLargestElement(intaiX[],intSizeX) { intiCounter; intiMaxIndex = 0; for(iCounter=0; iCounter<iSizeX; iCounter++) if(aiX[iMaxIndex] < aiX[iCounter] ) iMaxIndex = iCounter; return (iMaxIndex); }
Copying an Array into another Array void fnCopyArray(const intaiX[],intaiY[], intiLength) { intiCounter; for(iCounter=0;iCounter<iLength;iCounter++) aiY[iCounter] = aiX[iCounter]; }
Arrays in Function Prototype #include <stdio.h> const intiArraySize = 10; void fnInitializeArray (intaiX[], intiSizeX); void fnFillArray (intaiX[], intiSizeX); void fnPrintArray (const intaiX[], intiSizeX); intfnSumArray (const intaiX[], intiSizeX); intfnIndexLargestElement (const intaiX[], intiSizeX); void fnCopyArray (const intaiX[], intaiY[], intiLength);
Passing Arrays in Function Call int main() { intaiListA [iArraySize] = {0}; intaiListB [iArraySize]; fnPrintArray (aiListA, iArraySize); fnInitializeArray (aiListB, iArraySize); fnPrintArray (aiListB, iArraySize); fnFillArray (aiListA, iArraySize); fnPrintArray (aiListA, iArraySize); fnSumArray (aiListA, iArraySize); fnCopyArray (aiListA, aiListB, iArraySize); fnPrintArray (aiListB, iArraySize); return 0; }
Sample Program 5 #include <stdio.h> void fnPrintArray (const intaiA[][3]); // function prototype //function main begins program execution int main() { //initialize array1, array2, array3 int aiArray1 [2][3] = { {1, 2, 3}, {4, 5, 6} }; int aiArray2 [2][3] = { 1, 2, 3, 4, 5 }; int aiArray3 [2][3] = { {1, 2 }, { 4 } }; printf (“Values in array1 by row are : \n); fnPrintArray (aiArray1); printf ("Values in array2 by row are : \n"); fnPrintArray (aiArray2); printf ("Values in array3 by row are : \n"); fnPrintArray (aiArray3); return 0; } // end of main
Sample Program 5 (cont…) //function to display array with two rows and three columns void fnPrintArray (const intaiA[][3]) { intiRow; //row counter intiColumn; //column counter //loop through row for (iROw = 0; iRow <= 1; iRow++) { //output column values for (iColumn = 0; iColumn <= 2; iColumn++) { printf ("%d ", aiA[iRow][iColumn]); } //end inner for printf ("\n"); //start new line of output } //end outer for } //end function fnPrintArray
Sample Program 5 (cont…) Output Values in array1 by row are : 1 2 3 4 5 6 Values in array2 by row are : 1 2 3 4 5 0 Values in array3 by row are : 1 2 0 4 0 0