Consider a recursive function to find the maximum value in an array of integers.
ID: 3680490 • Letter: C
Question
Consider a recursive function to find the maximum value in an array of integers. The function declaration is: For this function, we need to know the size of the array and the starting index of the array (because both will change when a recursive call is made). You may assume that there is at least one value in the array: Describe the base case: Describe the reduction step: Describe why the reduction step will (i) solve the problem and (ii) move closer to the base case: Write the complete function definition for maxValue:Explanation / Answer
Please find the required solution and the sub questions in comments:
#include<stdio.h>
#define MAX 100
//method prototype
int maxValue(int vals[],int size,int start);
//main method implementation
int main()
{
//read data from console
int arr[MAX],size,i,max;
printf("Enter the size of the array: ");
scanf("%d",&size);
printf("Enter %d elements of an array: ", size);
for(i=0;i<size;i++)
scanf("%d",&arr[i]);
//find the largest element
max=maxValue(arr,size,0);//1.base case array initialization with start 0
printf("Largest element of an array is: %d ",max);
return 0;
}
//maxValue Method implementation
int maxValue(int vals[],int size,int start)
{
start++;
int max=(vals,size,start);
//2.reduction step
if(start < size)
{
if(max<vals[start])
max=vals[start];
}
return max;
}
sample output:
Enter the size of the array: 3
Enter 3 elements of an array: 1
3
2
Largest element of an array is: 3
Enter the size of the array: 3
Enter 3 elements of an array: 1
3
2
Largest element of an array is: 3