70 likes | 78 Views
This lecture discusses array parameters and auxiliary functions in static arrays, including reading and printing arrays, and reversing arrays.
E N D
ICOM 4015 Advanced Programming Lecture 11 Static Arrays II Reading: Chapter 4 Prof. Bienvenido Velez ICOM 4015
Static Arrays II Outline • Array parameters ICOM 4015
Example 1 - main function // Standard C++ header files #include <cmath> #include <iostream> // Forward declarations of local functions template <class T> swap(T& a, T& b); template <class T> int readData(istream& source, T data[], int maxlen); template <class T> void printArray(ostream& sink, T a[], int length); template <class T> void reverseArray(T a[], int length); // Main function int main() { // Define local array to hold input data const int ArrayLength = 100; float numbers[ArrayLength] = { 0.0 }; // Inititalize all cells to 0 // Read data from standard input int counter = readData(cin, numbers, ArrayLength); cout << "Read " << counter << " numbers" << endl; if (counter == 0) return 0; cout << "Original Array:" << endl; printArray(cout, numbers, counter); reverseArray(numbers, counter); cout << "Reversed Array:" << endl; printArray(cout, numbers, counter); } array-params.cc ICOM 4015
Example 1 - Auxiliary Functions // Auxiliary local functions template <class T> int readData(istream& source, T data[], int maxlen) { int counter = 0; while(counter < maxlen) { cout << "Next datum: "; float nextDatum; source >> nextDatum; if (source.eof()) break; data[counter++] = nextDatum; } return counter; } template <class T> void printArray(ostream& sink, T a[], int length) { for (int i=0; i<length; i++) { sink << a[i] << endl; } } template <class T> void reverseArray(T a[], int length) { int iterations = length / 2; for (int i=0; i<iterations; i++) { swap(a[i], a[length - i - 1]); } } template <class T> swap(T& a, T& b) { T temp = a; a = b; b = temp; } ICOM 4015 array-params.cc
Example 1 Output [bvelez@amadeus] ~/icom4015/lec11 >>array-params Next datum: 1 Next datum: 2 Next datum: 3 Next datum: 4 Next datum: 5 Next datum: 6 Next datum: 7 Next datum: 8 Next datum: 9 Next datum: 10 Next datum: Read 10 numbers Original Array: 1 2 3 4 5 6 7 8 9 10 Reversed Array: 10 9 8 7 6 5 4 3 2 1 [bvelez@amadeus] ~/icom4015/lec11 >> ICOM 4015
Anatomy of an Array Parameter Definition array name int f(int a[]) number of cells unspecified type of elements ICOM 4015
Array Parameters Summary • Arrays are passed by reference by default • Compiler ignores number of elements in parameter definition • Programmer typically passes array length as extra parameter ICOM 4015