Lecture 10

staff.fisika.ui.ac.id
  • No tags were found...

Lecture 10

ArraysAdhi Harmoko S, M.Komp


ArraysArrayConsecutive group of memory locationsSame name and typeTo refer to an element, specifyArray name and position numberFormat: arrayname[ position number ]First element at position 0n element array c:c[ 0 ], c[ 1 ]…c[ n - 1 ]Array elements are like normal variablesc[ 0 ] = 3;cout


Declaring ArraysDeclaring arrays - specify:NameType of arrayNumber of elementsExamplesint c[ 10 ];float hi[ 3284 ];Declaring multiple arrays of same typeSimilar format as other variablesExampleint b[ 100 ], x[ 27 ];


Examples Using ArraysInitializersint n[ 5 ] = { 1, 2, 3, 4, 5 };If not enough initializers, rightmost elements become 0If too many initializers, a syntax error is generatedint n[ 5 ] = { 0 }Sets all the elements to 0If size omitted, the initializers determine itint n[] = { 1, 2, 3, 4, 5 };5 initializers, therefore n is a 5 element array


Fig. 4.4: fig04_04.cpp1. Initialize array using a declaration2. Define loop3. Print out each array element


Fig. 4.4: fig04_04.cpp12345678910111213141516171819202122// Fig. 4.4: fig04_04.cpp// Initializing an array with a declaration.#include using std::cout;using std::endl;#include using std::setw;int main(){// use initializer list to initialize array nint n[ 10 ] = { 32, 27, 64, 18, 95, 14, 90, 70, 60, 37 };cout


Fig. 4.4: fig04_04.cppElement Value0 321 272 643 184 955 146 907 708 609 37


Fig. 4.4: fig04_04.cpp1. Initialize const variable2. Attempt to modify variable


Fig. 4.7: fig04_07.cpp123456789101112// Fig. 4.7: fig04_07.cpp// A const object must be initialized.int main(){const int x; // Error: x must be initializedx = 7; // Error: cannot modify a const variablereturn 0; // indicates successful termination} // end main


Fig. 4.7: fig04_07.cpp123456789101112// Fig. 4.7: fig04_07.cpp// A const object must be initialized.int main(){const int x; // Error: x must be initializedx = 7; // Error: cannot modify a const variablereturn 0; // indicates successful termination} // end mainFig04_07.cpp:Error E2304 Fig04_07.cpp 6: Constant variable 'x' must beinitialized in function main()Error E2024 Fig04_07.cpp 8: Cannot modify a const object infunction main()*** 2 errors in Compile ***


Fig. 4.7: fig04_07.cpp123456789101112// Fig. 4.7: fig04_07.cpp// A const object must be initialized.int main(){const int x; // Error: x must be initializedx = 7; // Error: cannot modify a const variablereturn 0; // indicates successful termination} // end mainNotice that const variables must beinitialized because they cannot bemodified later.Fig04_07.cpp:Error E2304 Fig04_07.cpp 6: Constant variable 'x' must beinitialized in function main()Error E2024 Fig04_07.cpp 8: Cannot modify a const object infunction main()*** 2 errors in Compile ***


Examples Using ArraysStringsArrays of charactersAll strings end with null ('\0')Examples:char string1[] = "hello";char string1[] = { 'h', 'e', 'l', 'l', 'o','\0’ };Subscripting is the same as for a normal arrayString1[ 0 ] is 'h'string1[ 2 ] is 'l'Input from keyboardchar string2[ 10 ];cin >> string2;Takes user inputSide effect: if too much text entered, data written beyond array


Fig. 4_12: fig04_12.cpp1. Initialize strings2. Print strings2.1 Define loop2.2 Print characters individually2.3 Input string3. Print string


Fig. 4_12: fig04_12.cpp23242526272829303132// output characters until null character is reachedfor ( int i = 0; string1[ i ] != '\0'; i++ )cout string1; // reads "there"cout


Fig. 4_12: fig04_12.cpp12345678910111213141516171819202122// Fig. 4_12: fig04_12.cpp// Treating character arrays as strings.#include using std::cout;using std::cin;using std::endl;int main(){char string1[ 20 ]; // reserves 20 characterschar string2[] = "string literal"; // reserves 15 characters// read string from user into array string2cout > string1; // reads "hello" [space terminates input]// output stringscout


Fig. 4_12: fig04_12.cpp23242526272829303132// output characters until null character is reachedfor ( int i = 0; string1[ i ] != '\0'; i++ )cout string1; // reads "there"cout


Fig. 4_12: fig04_12.cppEnter a string: Hello therestring1 is: Hellostring2 is: string literalstring1 with spaces between characters is:H e l l ostring1 is: there


Passing Arrays to FunctionsSpecify the name without any bracketsTo pass array myArray declared asint myArray[ 24 ];to function myFunction, a function call would resemblemyFunction( myArray, 24 );Array size is usually passed to functionArrays passed call-by-referenceValue of name of array is address of the first elementFunction knows where the array is storedModifies original memory locationsIndividual array elements passed by call-by-valuepass subscripted name (i.e., myArray[ 3 ]) to function


Passing Arrays to FunctionsFunction prototype:void modifyArray( int b[], int arraySize );Parameter names optional in prototypeint b[] could be simply int []int arraysize could be simply int


Fig. 4.14: fig04_14.cpp1. Define function to take in arrays1.1 Initialize arrays2. Modify the array (call by reference)2.1 Modify an element (call by value)3. Print changes.3.1 Function Definitions


Fig. 4.14: fig04_14.cpp12345678910111213141516171819202122// Fig. 4.14: fig04_14.cpp// Passing arrays and individual array elements to functions.#include using std::cout;using std::endl;#include using std::setw;void modifyArray( int [], intvoid modifyElement( int );); // appears strangeint main(){const int arraySize = 5; // size of array aint a[ arraySize ] = { 0, 1, 2, 3, 4 }; // initialize acout


Fig. 4.14: fig04_14.cpp2324252627282930313233343536373839404142434445// output original arrayfor ( int i = 0; i < arraySize; i++ )cout


Fig. 4.14: fig04_14.cpp4647484950515253545556575859606162// output value of a[ 3 ]cout


Fig. 4.14: fig04_14.cpp636465666768697071// in function modifyElement, "e" is a local copy of// array element a[ 3 ] passed from mainvoid modifyElement( int e ){// multiply parameter by 2cout


Fig. 4.14: fig04_14.cpp12345678910111213141516171819202122// Fig. 4.14: fig04_14.cpp// Passing arrays and individual array elements to functions.#include using std::cout;using std::endl;#include using std::setw;void modifyArray( int [], intvoid modifyElement( int );Functions can modify entire arrays.Individual array elements are notmodified by default.); // appears strangeint main(){const int arraySize = 5; // size of array aint a[ arraySize ] = { 0, 1, 2, 3, 4 }; // initialize acout


Fig. 4.14: fig04_14.cpp12345678910111213141516171819202122// Fig. 4.14: fig04_14.cpp// Passing arrays and individual array elements to functions.#include using std::cout;using std::endl;#include using std::setw;void modifyArray( int [], intvoid modifyElement( int );No parameter names in functionprototype); // appears strangeint main(){const int arraySize = 5; // size of array aint a[ arraySize ] = { 0, 1, 2, 3, 4 }; // initialize acout


Fig. 4.14: fig04_14.cpp4647484950515253545556575859606162// output value of a[ 3 ]cout


Fig. 4.14: fig04_14.cppEffects of passing entire array call-by-reference:The values of the original array are:0 1 2 3 4The values of the modified array are:0 2 4 6 8Effects of passing array element call-by-value:The value of a[3] is 6Value in modifyElement is 12The value of a[3] is 6


Sorting ArraysSorting dataImportant computing applicationVirtually every organization must sort some dataMassive amounts must be sortedBubble sort (sinking sort)Several passes through the arraySuccessive pairs of elements are comparedIf increasing order (or identical), no changeIf decreasing order, elements exchangedRepeat these steps for every element


Sorting ArraysExample:Original: 3 4 2 6 7Pass 1: 3 2 4 6 7Pass 2: 2 3 4 6 7Small elements "bubble" to the top


Case Study: Computing Mean, Median andMode Using ArraysMeanAverageMedianModeNumber in middle of sorted list1, 2, 3, 4, 5 (3 is median)Number that occurs most often1, 1, 1, 2, 3, 3, 4, 5 (1 is mode)


Searching Arrays: Linear Search and BinarySearchSearch array for a key valueLinear searchCompare each element of array with key valueUseful for small and unsorted arraysBinary searchCan only be used on sorted arraysCompares middle element with keyIf equal, match foundIf key < middle, repeat search through the first half of the arrayIf key > middle, repeat search through the last half of the arrayVery fast; at most n steps, where 2^n > # of elements30 element array takes at most 5 steps2 > 30


Multiple-Subscripted ArraysMultiple subscripts - tables with rows, columnsLike matrices: specify row, then column.Row 0Row 1Row 2Column 0 Column 1 Column 2 Column 3a[ 0 ][ 0 ]a[ 1 ][ 0 ]a[ 2 ][ 0 ]a[ 0 ][ 1 ]a[ 1 ][ 1 ]a[ 2 ][ 1 ]a[ 0 ][ 2 ]a[ 1 ][ 2 ]a[ 2 ][ 2 ]a[ 0 ][ 3 ]a[ 1 ][ 3 ]a[ 2 ][ 3 ]Array nameRow subscriptColumn subscriptInitializeint b[ 2 ][ 2 ] = { { 1, 2 }, { 3, 4 } };Initializers grouped by row in bracesint b[ 2 ][ 2 ] = { { 1 }, { 3, 4 } };1 23 41 03 4


Multiple-Subscripted ArraysReferenced like normalcout

More magazines by this user
Similar magazines