#include #include #include using namespace std; // Selects a random value from the array giving the last value a 50% // chance to be selected, the previous to last 25%, and so on. Used as // an example of tail recursion. int randomSelect (int A[], int size) { if (size == 0) return -1; else if (size == 1) return A[0]; else if (rand() % 2 == 0) return A[size-1]; else return randomSelect(A, size-1); } // Outputs the numbers from n down to 0 recursively. void printN(int n) { if (n < 0) cout << endl; else { cout << n << " "; printN(n - 1); } } // Counts the occurrences of the value in the array using recursion. int countVal (int A[], int size, int val) { if (size == 0) return 0; else if (A[size - 1] == val) return 1 + countVal(A, size-1, val); else return countVal(A, size - 1, val); } // Testing for the random select function. int main() { int arr[] = {12, 3, 6, 7, 2, 9}; int brr[] = {1, 3, 2, 7, 1, 7, 2, 7}; srand(time(NULL)); cout << "Selection: " << randomSelect(arr, 6) << endl; printN(8); cout << "Count of 7 in brr: " << countVal(brr, 8, 7) << endl; return 0; }