75.2k views
4 votes
write a c recursive function that finds the maximum value in an array (or vector) of integers without using any loops. you may assume the array will always contain at least one integer. do not modify the array

User Vexe
by
5.5k points

1 Answer

4 votes

If you want to predefine the vector array you can use this code.

#include <bits/stdc++.h>

int eval(std::vector<int> v, int n) {

return (n==1) ? v.at(0) : std::max(v.at(n-1), eval(v,n-1));

}

int main() {

std::vector<int> vector {1,2,3,4,90,1234,9,0,45,-7};

std::cout << "The maximum is: " << eval(vector,vector.size());

return 0;

}

If you want the user to fill the vector array, you should use this.

#include <bits/stdc++.h>

int eval(std::vector<int> v, int n) {

return (n==1) ? v.at(0) : std::max(v.at(n-1), eval(v,n-1));

}

int main() {

std::cout << "How many elements will you append?: ";

int size; std::cin>>size;

std::vector<int> vector;

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

std::cout << i+1 << ". element: ";

int temp; std::cin>>temp; vector.push_back(temp);

}

std::cout << "The maximum is: " << eval(vector,vector.size());

return 0;

}

write a c recursive function that finds the maximum value in an array (or vector) of-example-1
write a c recursive function that finds the maximum value in an array (or vector) of-example-2
User Tim Saylor
by
6.5k points