C++ PROGRAM RECURSION - functions should be written by recursion int find int it
ID: 3769063 • Letter: C
Question
C++ PROGRAM
RECURSION - functions should be written by recursion
int find int item, const int array[], int elements elements is the number of elements in the array The function's job is to locate the position of the first occurrence of item's value in the array. For example, if array held 12, 4, 6, 8, 10, 8, 6,4, 2), then find 8, array, 9 would return 3, because the first 8 occurs in array[3]. If item is not in the array, the function should return INT MAX int howMany int item, const int array[], int elements Same args as the last function. This function's job is to return the number of times the value of item appears in the array For example, if array held 12, 4, 6, 8, 10, 8, 6, 4,2, then how Many 8, array, 9) would return 2, because there are 28's in the array.Explanation / Answer
Answer 1) I have used the function findIndex instead of find and created the same program to find the index of a given element in the array using recursion.
#include <iostream>
#include <iomanip>
#include <algorithm>
#include <iterator>
using namespace std;
int FindIndex(int *arr, int size, int num)
{
int index = 0;
while(index < size){
if(arr[index] == num){
return index;
}
index += abs(num - arr[index]);
}
return -1;
}
int main(int argc, char* argv[])
{
int arr[] = {4, 5, 6, 5, 6, 7, 8, 9, 10, 9, 10};
copy(begin(arr), end(arr), ostream_iterator<int>(cout, ","));
cout << endl;
for(int i = 0; i < 15; ++i){
cout << "Find " << setw(2) << left << i << " at ";
cout << FindIndex(arr, sizeof(arr) / sizeof(int), i);
cout << endl;
}
return 0;
}
Output:
4,5,6,5,6,7,8,9,10,9,10,
Find 0 at -1
Find 1 at -1
Find 2 at -1
Find 3 at -1
Find 4 at 0
Find 5 at 1
Find 6 at 2
Find 7 at 5
Find 8 at 6
Find 9 at 7
Find 10 at 8
Find 11 at -1
Find 12 at -1
Find 13 at -1
Find 14 at -1
Press any key to continue . . .
Answer 2) I have used count instead of howMany to count the number of occurrences of a particular number,
Output:
3 ( since 2 appears 3 times in the array)
Answer 2)
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.