C++ max of an array using recursion issue -


i have program finds largest integer in array using recursion, keeps returning last number entered no matter value instead of largest number. how 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 = 0; < size; a++)   {       cout << "enter 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 ( < size )   {       if ( largest < digits[i])           largest = digits[i];        maximum( digits, size, largest, + 1);   }   return largest; } 

first use index variable in main()

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

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

please check out changes. read code. understand mistakes.

when designing recursion think of few things first-

  • the base condition. (this stops recursion).

  • the recursive step. (where calculate based on previous calculation)

  • combine step- have combine them (value @ stage , value got recusive step) correct answer. step not required in cases.


Comments

Popular posts from this blog

tcpdump - How to check if server received packet (acknowledged) -