简体   繁体   中英

C++ max of an array using recursion issue

I have this program that finds the largest integer in an array using recursion, but it keeps returning the last number entered no matter what the value instead of the largest number. How do i fix this?

#include <iostream>

using namespace std;

int maximum(int digits[], int size, int largest, int i);

void main()
{
  const int size = 3;
  int digits[size];
  int n = 0, x = 0;

  for(int a = 0; a < size; a++)
  {
      cout << "Enter an integer <" << ++x << " out of " << size << ">: ";
      cin >> digits[n];
  }

  cout << "\nThe largest digit is, " << maximum(digits, size, 0, 0) << ", thank you!\n";
  cout << endl;
}


int maximum(int digits[], int size, int largest, int i)
{
  if ( i < size )
  {
      if ( largest < digits[i])
          largest = digits[i];

      maximum( digits, size, largest, i + 1);
  }
  return largest;
}

It should be return maximum( digits, size, largest, i + 1);

Live example .

First use the index variable properly in main()

  for(int a = 0; a < size; a++)
  {
      cout << "Enter an integer <" << ++x << " out of " << size << ">: ";
      cin >> digits[a];//-->Use the index varible correctly.
  }

int maximum(int digits[], int size, int largest, int i)
{
  if(i==size-1)
    return digits[i]; //The base case is specified here.
  if ( i < size )
  {
      int temp= maximum( digits, size, largest, i + 1);
      if ( digits[i] < temp)
          largest =temp;
      else
         largest=digits[i];

  }
  return largest;
}

Please check out the changes. Carefully read the code. You will understand your mistakes.

When designing recursion think of few things first-

  • The base condition. (This stops the recursion).

  • The recursive step. (Where you will calculate something based on previous calculation)

  • Combine step- You have to combine them (value at this stage and value got from recusive step) to get the correct answer. This step is not required in some cases.

int biggestOne(int integerArray[], int lengthOfArray, int max)
{
    if (lengthOfArray==0) return max;
    if (max < integerArray[lengthOfArray-1]) max = integerArray[lengthOfArray-1];
    return biggestOne(integerArray,lengthOfArray-1,max); 
}

int main()
{
    int array[] = {7,2,9,10,1};
    int arrSize = sizeof(array)/sizeof(array[0]); //returns length of the array

    cout <<"Biggest number in the array: " << biggestOne(array,arrSize,0) << endl;
    return 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM