I need to use recursion to find the largest int in an array. What I have so far is

#include <iostream>
using std::cout;
using std::endl;

int maxArray(int anArray[], int size);

/**
 *The main method
 *
 *@param myArray[] The array we are searching
 *
 *@param sizeOfArray The size of the array
 *
 *@param largestNumber  The largest number in the array
 */
int main(){

  int myArray[] = { 1, 6, 8, 3 };

  int sizeOfArray = sizeof(myArray)/sizeof(*myArray);

  int largestNumber = maxArray(myArray, sizeOfArray);

  cout<< "the largest number of the array is " << largestNumber << endl;

  return 0;

}//end main

/**
 *This method finds the largest int in an array
 *
 *@param anArry The array of integers
 *
 *@param size The size of the array
 *
 *@return The largest number in the array
 */
int maxArray(int anArray[], int size){

  if(size == 0){

    cout << "empty array" << endl;

  }

  if(size == 1 ){

    return anArray[0];

  }else{
    
    return maxArray(anArray, size-1);
    
  }

}//end maxArray

So I can get down to finding the first item in the array, but I cant figure out how I would go about getting to the 2nd, 3rd, 4th, etc items in the array using a recursive function and then once I get down to the one int how would I go about comparing that int to another int in the array. Im confused, any suggestions on how I can get over my hump of at least getting to the next element in the array. Id appriciate any suggestions/help/examples from other programs or any sites that would guide me in the right direction. And no I dont want you to do this for me, I just want a hint or suggestion so I can get unstuck. Thanks.

Dani AI

Generated

A simple way to think about the recursion is: the maximum of the first n elements is the larger of (a) the maximum of the first n-1 elements and (b) the nth element. You need two base cases: handle an empty array explicitly, and when n == 1 just return the single element. Avoid printing inside the algorithm; either enforce the precondition that size > 0 or signal the error (e.g., throw).

Here is a compact, correct version that compares the last element to the recursive result:

#include <stdexcept>
#include <algorithm> // for std::max (optional)

int maxArray(const int* a, int n) {
    if (n <= 0) throw std::invalid_argument("array must be non-empty");
    if (n == 1) return a[0];
    int m = maxArray(a, n - 1);
    return m > a[n - 1] ? m : a[n - 1]; // or: return std::max(m, a[n - 1]);
}

Notes and tips:

  • Complexity is O(n), with recursion depth n. For very large arrays prefer an iterative approach or the standard library.
  • If recursion is a requirement for learning, this pattern is idiomatic. In production C++, prefer *std::max_element(begin, end) from <algorithm> (cppreference on max_element) or std::max for two values (cppreference on max).
  • You can also write an index-based variant: recurse on i+1 to n, then compare with a[i]. This avoids slicing the array but has the same complexity.

Recommended Answers

All 3 Replies

Ironically, this isn't the greatest example of recursion; it could probably be solvedd with a simple loop. :rolleyes:

However, since your instructor requires you to do it, here is basically what you should do when you actually get to the point where it's going to call itself: call the function, and instead of returning the value, store it in a variable. If this value is greator than the one it already has, return this latest value. Otherwise return the original value.

To make it clearer:

int maxArray(int anArray[], int size){

  if(size == 0){

    cout << "empty array" << endl;

  }

  if(size == 1 ){

    return anArray[0];

  }else{
    
    tempVariable = maxArray(anArray, size-1);
 // if this tempVariable is larger than anArray[size]:
//     return tempVariable
// otherwise just return  anArray[size]
    
  }
}//end maxArray

Awesome. Thank you.

Try this one

#include<iostream.h>
#include<conio.h>


int find(int *a,int start,int end)
{


	if(start<end)
	{

		if(a[start]<a[end])
		{

		cout<<"1st Arrys condition"<<a[start]<<" "<<a[end]<<endl;
		return find(a,start+1,end);

		}
		else
		cout<<"2nd Arrys condition"<<a[start]<<" "<<a[end]<<endl;
		return find(a,start,end-1);

	}
	cout<<"Last= "<<a[end]<<endl;
}

void main()
{
clrscr();

const int size=8;
int arr[size]={7,6,13,12,2,9,5,99};

for(int i=0;i<size;i++)
{
	cout<<arr[i]<<" ";
}
cout<<endl;
find(arr,0,size-1);

getch();
}
commented: void main, non-standard code, Giving code to noob. There are multiple reason for a bad reputation -1
commented: Copy/paste answer for no reason (http://www.daniweb.com/forums/post867983.html#post867983) and TWO YEARS too late -6
commented: Though it is non-standard code and you answered lately and you gave away code. It is really a neat recursive algorithm though there is no case if a[start]==a[end]; +3
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.