Complementary task for topic: 10
M Nemeth · 2023-08-29 15:21:04.633218'
Recursion: count occurances
Recursion: count occurances
Write a program to find the number of occurrences of a target element in an array using recursion.
Hint:
Solution
#include
// Function to calculate the number of occurrences of a target element in an array using recursion
int countOccurrences(int arr[], int size, int target, int currentIndex) {
if (currentIndex == size) {
return 0; // Base case: Reached the end of the array
} else {
int count = (arr[currentIndex] == target) ? 1 : 0;
return count + countOccurrences(arr, size, target, currentIndex + 1);
}
}
int main() {
int size, target;
printf("Enter the size of the array: ");
scanf("%d", &size);
if (size <= 0) {
printf("Error: The size of the array should be greater than 0.\n");
return 1;
}
int arr[size];
printf("Enter %d elements of the array:\n", size);
for (int i = 0; i < size; i++) {
scanf("%d", &arr[i]);
}
printf("Enter the target element to find its occurrences: ");
scanf("%d", &target);
int occurrences = countOccurrences(arr, size, target, 0);
printf("The number of occurrences of %d in the array is: %d\n", target, occurrences);
return 0;
}
Explanation
The main function then calls the countOccurrences function, passing the array, its size, the target element, and the initial index (0) as arguments. The countOccurrences function uses recursion to calculate the number of occurrences of the target element in the array. It has a base case where the currentIndex reaches the end of the array, in which case it returns 0. Otherwise, it checks if the element at the currentIndex matches the target element and increments the count accordingly. It then makes a recursive call with an increased currentIndex to continue the search.