+92 332 4229 857 99ProjectIdeas@Gmail.com

How to find largest in an integer array recursively (C++ Tutorial)


Finding largest in an integer array recursively
FindLargestRecursive() finds the largest in an integer array recursively and returns the largest value. It takes 4 parameters:
arr takes the array.
i takes the index of the array.
size takes the size of the array.
largest holds the largest element of the array.
Code of FindLargestRecursive()
int FindLargestRecursive( int arr[] , int i , int size , int largest )
{
      if ( i < size )
      {
            if ( arr[i] > largest )
                  largest = arr[i];
            return FindLargestRecursive( arr , i + 1 , size, largest );
      }
      return largest;
}
Summary of FindLargestRecursive()
FindLargestRecursive() starts from the first index of the array and recursively calls itself until i becomes equal to or greater than the size of array, at each function call the current element is checked against the largest element, if the current element at arr[i] is larger than the element in the largest variable, then the current element is saved in the largest variable.
At each recursive function call, the current index i is incremented by 1.
At the end, value in the largest variable is returned from the function.
Example (C++)
#include "stdafx.h"
#include "iostream"
#include "conio.h"

using namespace std;

int FindLargestRecursive( int arr[] , int i , int size , int largest )
{
      if ( i < size )
      {
            if ( arr[i] > largest )
                  largest = arr[i];
            return FindLargestRecursive( arr , i + 1 , size, largest );
      }
      return largest;
}

int main()
{
      const int size1 = 10;
      int arr1[size1] = {10,20,30,40,50,60,60,70,80,90};
      cout << FindLargestRecursive( arr1 , 1 , size1 , arr1[0] ); //    90
      cout << endl;

      const int size2 = 10;
      int arr2[size2] = {85,20,30,40,50,60,60,70,75,80};
      cout << FindLargestRecursive( arr2 , 1 , size2 , arr2[0] ); //    85
      cout << endl;

      const int size3 = 10;
      int arr3[size3] = {1,2,3,4,5,6,7,8,9,0};
      cout << FindLargestRecursive( arr3 , 1 , size3 , arr3[0] ); //      9
      cout << endl;

      const int size4 = 10;
      int arr4[size4] = {10,20,30,40,50,60,70,80,90,100};
      cout << FindLargestRecursive( arr4 , 1 , size4 , arr4[0] ); //    100
      cout << endl;

      const int size5 = 10;
      int arr5[size5] = {5,10,15,20,25,30,35,40,45,50};
      cout << FindLargestRecursive( arr5 , 1 , size5 , arr5[0] ); //    50
      cout << endl;
     
      _getche();
      return 0;
}
Output
90
85
9
100
50

0 comments: