Last active
March 29, 2022 22:00
-
-
Save ruggeri/d66fe5798f85c48ddcf59738b36da272 to your computer and use it in GitHub Desktop.
Calculate A Maximum Value Recursively
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <stdexcept> | |
int max(int numbers[], unsigned int len) | |
{ | |
std::cout << "len=" << len << ": starting function." << std::endl; | |
if (len == 0) | |
{ | |
throw std::invalid_argument("len must not be zero"); | |
} | |
else if (len == 1) | |
{ | |
std::cout << "len=" << len << ": base case returning " << numbers[0] << std::endl; | |
return numbers[0]; | |
} | |
else | |
{ | |
std::cout << "len=" << len << ": about to launch recursive call with len=" << len - 1 << std::endl; | |
int maxOfRest = max(numbers, len - 1); | |
std::cout << "len=" << len << ": recursive call complete." << std::endl; | |
int finalNumber = numbers[len - 1]; | |
std::cout << "len=" << len << ": comparing maxOfRest=" << maxOfRest << " and finalNumber=" << finalNumber << std::endl; | |
if (maxOfRest > finalNumber) | |
{ | |
std::cout << "len=" << len | |
<< ": complete, returning " << maxOfRest << std::endl; | |
return maxOfRest; | |
} | |
else | |
{ | |
std::cout << "len=" << len | |
<< ": complete, returning " << finalNumber << std::endl; | |
return finalNumber; | |
} | |
} | |
} | |
int main() | |
{ | |
int numbers[5] = {19, 53, 31, 43, 24}; | |
int maxValue = max(numbers, 5); | |
std::cout << "the max is: " << maxValue << std::endl; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment