Skip to content

Instantly share code, notes, and snippets.

@MattMSumner
Created April 12, 2017 23:02
Show Gist options
  • Save MattMSumner/a81ca14fa5d1ed65acf1862206b294e0 to your computer and use it in GitHub Desktop.
Save MattMSumner/a81ca14fa5d1ed65acf1862206b294e0 to your computer and use it in GitHub Desktop.
Recursion in c++
int findLargest(int array[])
{
int arrayLength = sizeof(array)/sizeof(array[0]);
int firstElement = array[0];
int newArray[] = // This needs to be a new array without the original array's first element.
if (arrayLength == 1) {
return max(firstElement, newArray[0])
} else {
return max(firstElement, findLargest(newArray));
}
}
@Ashtag16
Copy link

//using Vectors instead of Array so code changed appropriately

int list_max(std::vector &list) {

int firstElement = list.at(0);
vector<int> tempvect = list;
tempvect.erase(tempvect.begin());
if (tempvect.size() == 1) {
    return max(firstElement, tempvect.at(0));
} else {
    return max(firstElement, list_max(tempvect));
}

}

@farmanhasnain12
Copy link

farmanhasnain12 commented Dec 17, 2019

This probelm can also be solved without using the TempArray/NeewArray

// Recursive programme to print the maximum element in the Array

`

int findmax(int arr[], int size)

{

if (!size)

	return arr[0];

if (arr[size - 1] > findmax(arr, size - 1))

	return arr[size - 1];

	return findmax(arr, size - 1);

}

int main()

{

int array[10] = { 4,3,2,10,7,29,-1,-2,10,1 };

cout << findmax(array, 10) << endl;

}
`

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment