c++ arrays as parameters

Arrays are a collection of like data with a single name.
Elements of the array are accessed using the name and a unique array index.

          (cplusplus.com)


. arrays as parameters
Arrays are passed by reference only - symbol '[ ]' used when declaring an array as a parameter - size of the array is OMITTED (ignored if supplied) Base Address of an Array is address of the FIRST component - base address of array, 'list' is address of the component 'list[0]' - so, parameter '&list[0]' same as 'list' - base address of actual array is passed Functions canNOT return a value of type array

#include <iostream> using namespace std; // proto: array as parameter void print( int array[], int sz ); void print2( int array[10], int sz ); void print3( const int array[], int sz ); void print4( int *array, int sz ); int main( ) { int list[ 10 ], size = 10; // what is in list? for ( int i=0; i < 10; i++ ) list[ i ] = i; // call is ok - name of array, list, is actually the address print( list, size ); // call is ok - address of first element - same as list print( &list[0], size ); //other calls to other print functions print2( list, size ); print3( list, size ); print4( list, size ); system("pause"); return 0; } // function prints the contents of the passed array void print( int array[], int sz ) { for ( int i=0; i<sz; i++ ) cout << array[ i ] << " "; cout << endl; return; } // ** ALL of these definitions of 'print' are ok also... // print the contents of the array // CAN include size, but IGNORED (will compile) void print2( int array[10], int sz ) { for ( int i=0; i<sz; i++ ) cout << array[ i ] << " "; cout << '\n'; return; } // ** this protects (const keeps function from modifying) void print3( const int array[], int sz ) { //Reserved word 'const' in declaration of formal parameter //prevents function from changing actual parameter for ( int i=0; i<sz; i++ ) cout << array[ i ] << " "; cout << '\n'; return; } // also can define as a pointer void print4( int *array, int sz ) { //different way to access array via pointer for ( int i=0; i<sz; i++ ) cout << *(array + i) << " "; // don't need () as '+' binds before '*' cout << '\n'; return; }

EXAMPLE: ======== Why this output?? ^^^^^^^^^^^^^^^^^ #include <iostream> using namespace std; void printList( int list[], int size ); const int SZ = 10; int main( void ) { int list[ SZ ]; for ( int i = 0; i < SZ; i++ ) list[ i ] = i; // 0 - 9 printList( list, SZ); printList( &list[0], SZ ); printList( &list[5], SZ ); return 0; } void printList( int list[], int size ) { cout << endl; for ( int i=0; i < size; i++ ) cout << list[ i ] << ' '; cout << endl; return; }

. code: arrays in function calls

C++ Primer Plus Chapter 7
C++ code examples 5-7, 14


. fibonaccis in an array
/* create a function called fib2 that has 2 params: an unsigned int array an int telling how many cells in the array start with 0, 1 (0, 1, 1, 2, 3, 5, 8, etc...) fill in the array with the fib sequence create a function called fib3 that has 3 params: an unsigned int array an int telling how many cells in the array an int starting num fill in the array with the fib sequence [The term Fibonacci sequence is also applied more generally to any function g from the integers to a field for which g(n+2) = g(n) + g(n+1).] w */ #include <iostream> using namespace std; void fib2( unsigned int[], int ); void fib3( unsigned int[], int, int ); void print( unsigned int[], int ); int main ( void ) { unsigned int fibby[ 100 ]; fib2( fibby, 10 ); print( fibby, 10 ); fib3( fibby, 100, 8 ); print( fibby, 100 ); return 0; } ------------ void fib2( unsigned int list[], int sz ) { list[ 0 ] = 0; list[ 1 ] = 1; for ( int i=2; i<sz; i++ ) list[ i ] = list[ i-1 ] + list[ i-2 ]; return; } ----------------- void fib3( int unsigned list[], int sz, int start ) { list[ 0 ] = start; list[ 1 ] = start + 1; for ( int i=2; i<sz; i++ ) list[ i ] = list[ i-1 ] + list[ i-2 ]; return; } --------------------- void print( unsigned int list[], int sz ) { for ( int i=0; i<sz; i++ ) cout << list[ i ] << " "; cout << "\n\n"; return; }

. array code examples
// // searching arrays for single items, multiple items, counting items, etc... // void arraystuff() { const int RANGE = 40; // arrays int ai[ 50 ]; // |0|1|2|3|4|5|6|7|8|9|...|49| indexes int suba[ 5 ]; // |0|1|2|3|4| indexes int x, count, i, j; bool found; cout << "Create a large array of 50 items and a small array of 5 items.\n" << "Search large array for a random number and report where first found.\n" << "Search large array for a random number and report how many found.\n" << "Report if any items in small array are in large array.\n" << "Report if ALL of small array items are in large array.\n\n"; --------------------------------------------------- // put RANDOM nums in arrays indexes and print for ( i=0; i<50; i++ ) { cout << setw(3) << ( ai[i] = rand()%RANGE ); if ( i == 24 ) cout << endl; // format } cout << "\n\n"; for ( i=0; i<5; i++ ) cout << setw(3) << ( suba[i] = rand()%RANGE ); cout << "\n\n"; --------------------------------------------------- // find some random item ONCE in big array found = false; x = rand( ) % RANGE; // get some number for ( i=0; i < 50; i++ ) if( x == ai[i] ) { found = true; break; // found it ONCE, so quit looking } // let 'em know if it was found if ( found ) cout << "First found item \'" << x << "\' at index " << i << " in array." << endl; else cout << '\'' << x << "\' not found even once in array." << endl; --------------------------------------------------- // find some random item in big array & COUNT TIMES found x = rand( ) % RANGE; // get some number count = 0; for ( i=0; i < 50; i++ ) if( x == ai[i] ) count++; // let 'em know how many times it was found cout << "Found item \'" << x << "\' " << count << " times in array.\n"; --------------------------------------------------- // find if ANY ONE sub-array member is in list // int ai[50]; // |0|1|2|3|4|5|6|7|8|9|...|49| // int suba[5]; // |0|1|2|3|4| found = false; for ( i=0; i < 50; i++ ) { for ( j=0; j<5; j++ ) { if ( suba[j] == ai[i] ) { found = true; // we found one, break out of inner loop cout << setw(3) << j << " = j, subarray " << setw(3) << suba[j] << endl << setw(3) << i << " = i, array " << setw(3) << ai[i] << endl << endl; break; } } // this breaks out of the outer loop if ( found ) break; // we found one, so we can quit now } // let 'em know... if ( found ) cout << "A sub-array item WAS found in array \n"; else cout << "NO sub-array item found in array\n"; --------------------------------------------------- // find if ENTIRE sub-array is in list // int ai[50]; // |0|1|2|3|4|5|6|7|8|9|...|49| // int suba[5]; // |0|1|2|3|4| for ( i=0; i<5; i++ ) { // assume that none have been found found = false; for ( j=0; j<50; j++ ) { if ( suba[i] == ai[j] ) { found = true; // we found one - keep looking! break; // out of j loop } } // oh no! one of the small array items wasn't found if ( !found ) break; // out of i loop } // let 'em know... if ( found ) cout << "All sub-array items WERE found in array \n"; else cout << "All sub-array items NOT found in array\n"; --------------------------------------------------- // int ai[50]; // |0|1|2|3|4|5|6|7|8|9|...|49| // int suba[5]; // |0|1|2|3|4| // COUNT # of times each item in sub-array is in array int times[5]={0,0,0,0,0}; for ( i=0; i<5; i++ ) { for ( j=0; j<50; j++ ) { if ( suba[i] == ai[j] ) { times[i]++; // break; // out of j loop } } //if (!found) break; // out of i loop } // ?? for ( i=0; i<5; i++ ) cout << setw(3) << suba[i]; cout << endl; for ( i=0; i<5; i++ ) cout << setw(3) << times[i]; cout << endl; return; }

. code example: removing an item from array

  Simple removal from a list - not good for large list


// delete and MOVE all the items in the list "over one" // param: the list, the length of list and item index to remove void removeAt( int list[], int& len, int index ) { // check if index is in range of list if ( index< 0 || index > len-1 ) { cout << "Position of item to be deleted is out of range."<< endl; if ( index < 0 ) cout << "Position of deleted item must be nonnegative.\n"; else cout << "There are only " << len << " items in the list.\n" } else // move all the items "over one" from the deletion spot { for ( int i=index; i<len; i++ ) list[ i ] = list[ i + 1 ]; // adjust the length of the list len--; } return; }

. code example: comparing arrays
Problem ======= How do we check accuracy of a transmitted message? One solution: transmit the same message twice at destination, both copies of message compared bit by bit if corresponding bits are the same message is error-free
Write program to check if message received is error-free Assume code in the message is a sequence of digits (0 to 9) Max length of the msg is 250 digits First number is the length of msg
Example ======= Message 9 2 7 8 3 5 6 is 7 digits long Encode as 7 9 2 7 8 3 5 6 ^ length Send (twice) as 7 9 2 7 8 3 5 6 7 9 2 7 8 3 5 6 Input: file containing the code and its copy Output: code, its copy, and message if code is error-free Code Code Copy 9 9 2 2 7 7 8 8 3 3 5 5 6 6 * Valid
Algorithm Design ================ main ==== Open files Call readCode, to read code, passing in lengthCodeOK & array ^^^^^^^^ If ( lengthCodeOk is a valid length ) Call compareCode passing in array & length ^^^^^^^^^^^ Else Output an error message - length bad Terminate Program -------------- readCode ======== Read length of code If length of code > 250 OR length of code < 1 lengthCodeOk, a ref parameter, is set false and function returns Else Loop length times Read msg code item and store in next array slot Return lengthCodeOk indicating whether code was read successfully ------------------ compareCode ======== pass in the code (array) & its length set bool variable codeOk true read length of copy of the code If length of code and its copy are not the same Output error message return Else Loop length times read the next digit of the code's copy Output corresponding digit If the corresponding digits are not the same, output error message set the flag codeOk to false If the bool variable codeOk is true Output a message indicating VALID else Output an error message

----------------------------------

#include <iostream> #include <fstream> #include <iomanip> using namespace std; const int maxCodeSize = 250; void readCode( ifstream& infile, int list[], int& length, bool& lenCodeOk ); void compareCode( ifstream& infile, ofstream& outfile, int list[], int length ); int main( ) { int codeArray[ maxCodeSize ]; //array to store code int codeLength; // length of the code bool lengthCodeOk; // indicate if length of code <= 250 ifstream incode; // input file stream variable ofstream outcode; // output file stream variable char inputfile[25]; // name of input file char outputfile[25];// name of output file // get input file name and open cout << "Enter the input file name: "; cin >> inputfile; cout << endl; incode.open( inputfile ); //Step 2 if ( !incode ) { cout << "Cannot open the input file." << endl; return 1; } // get output file name and open cout << "Enter the output file name: "; cin >> outputfile; cout << endl; outcode.open( outputfile ); // read and compare code readCode( incode, codeArray, codeLength, lengthCodeOk ); if ( lengthCodeOk ) compareCode( incode, outcode, codeArray, codeLength ); else { cout << "Length of the code must be <= " << maxCodeSize << endl; incode.close(); } outcode.close(); return 0; }
// get length, get FIRST msg and store in array void readCode( ifstream& in, int list[], int& length, bool& lenCodeOk ) { int count; lenCodeOk = true; // get the length of the code in >> length; if (length > maxCodeSize) { lenCodeOk = false; return; } // get the code for (count = 0; count < length; count++) in >> list[count]; return; }
// get length, get SECOND msg and compare void compareCode( ifstream& in, ofstream& out, int list[], int length ) { int length3; int digit; bool codeOk; int count; codeOk = true; // get length in >> length3; if (length != length3) { cout << "The original code and its copy are not of" << " the same length." << endl; return; } // header, first msg, second msg out << "Code Code Copy" << endl; for ( count = 0; count < length; count++ ) { in >> digit; out << setw(7) << list[count] << setw(20) << digit; // compare the first and second msg if ( digit != list[ count ] ) { out << " code digit not the same" << endl; codeOk = false; } else out << endl; } // let 'em know if ( codeOk ) out << "Valid." << endl; else out << "Error in transmission. Retransmit!!" << endl; return; }