// filename: evensourceByFunctions.cpp // // Pointer Exercise #6 // Write a function countEven(int*, int) which receives an integer array // and its size, and returns the number of even numbers in the array. // // An example of the use of pointers to traverse an array. // // In this program, three functions are shown, using the array index ([]) notation // and the pointer (*) notation. They are completely equivalent in the funcionality // -- they are only syntactic variations. #include using namespace std; // prototypes int countEven1(int a[], int size); // use the [] notation int countEven2(int* a, int size); // use the * notation and offset int countEven3(int* a, int size); // use the * notation and iterator int main() { int ar[5] = { 5, 2, 9, 4, 0 }; int count; count = countEven1(ar, 5); cout << "countEven1 returned " << count << endl; count = countEven2(ar, 5); cout << "countEven2 returned " << count << endl; count = countEven3(ar, 5); cout << "countEven3 returned " << count << endl; return 0; } // This function uses the array index ([]) notation. // Note the array parameter is "int a[]", NOT "int[] a" as in Java. int countEven1(int a[], int size) { int countLocal = 0; for (int i = 0; i < size; i++) { if (a[i] % 2 == 0) { countLocal++; } } return countLocal; } // This function uses the pointer (*) notation. // The pointer a is in the parameter, and it points to the beginning // of the array passed in from the calling function. // Each element in the array is accessed by its offset from the // beginning of the array. int countEven2(int* a, int size) { int countLocal = 0; for (int i = 0; i < size; i++) { if (*(a + i) % 2 == 0) { countLocal++; } } return countLocal; } // This function uses the pointer (*) notation. // The pointer a is in the parameter, and it points to the beginning // of the array passed in from the calling function. // The pointer gets advanced (by ++) when the code iterates through the array. int countEven3(int* a, int size) { int countLocal = 0; for (int i = 0; i < size; i++) { if (*a % 2 == 0) { countLocal++; } a++; // advance the pointer a by 1 slot } return countLocal; }