133k views
5 votes
The maximum-valued element of an integer-valued array can be recursively calculated as follows: If the array has a single element, that is its maximum (note that a zero-sized array has no maximum) Otherwise, compare the first element with the maximum of the rest of the array-- whichever is larger is the maximum value. Write an int function named max that accepts an integer array, and the number of elements in the array and returns the largest value in the array. Assume the array has at least one element.

User Kadia
by
4.2k points

1 Answer

3 votes

Solution :

#include <iostream>

using namespace std;

//Function Declaration

int max(int arr[],int size);

int main()

{

//Declaring variable

int size;

while(true)

{

cout<<"Enter the no of elements in the array :";

cin>>size;

if(size<=0)

{

cout<<"Invalid.Must be greaterthan Zero"<<endl;

continue;

}

else

break;

}

//Creating an array

int arr[size];

/* getting the inputs entered by

* the user and populate them into array

*/

for(int i=0;i<size;i++)

{

cout<<"Enter element#"<<i+1<<":";

cin>>arr[i];

}

//calling function

int maximum=max(arr,size);

//Displaying the output

cout<<"The maximum Element in the Array is :"<<maximum<<endl;

return 0;

}

/* Function implementation which finds

* the maximum element in the array and return it

*/

int max(int arr[],int size)

{

//Declaring the static variables

static int k=0,maximum=-999;

/* This if block will execute only if the value of k

* is less than the size of an array

*/

if(k==size-1)

{

return arr[0];

}

else if(size-1>k)

{

if(arr[k]>maximum)

maximum=arr[k];

//Incrementing the k value

k++;

//Calling the function

max(arr,size);

}

return maximum;

}

User Prabhakar Manthena
by
4.4k points