carraysrecursionconio

program to find minimum and maximum element of array using recursion


I want to find the Maximum and Minimum element of an array using recursion. Here is the program I've written, I've gone through the logic and its seem to be perfect. But when I compile the program the program get stuck after taking input.

Here's my program:

#include<stdio.h>
#include<conio.h>

int max(int a[], int n);
int min(int a[], int n);

void main(){
    int a[100],n,i,maxi,mini;
    clrscr();
    printf("Enter the number of elements ");
    scanf("%d",&n);
    printf("Enter the elements of array ");
    for(i=0;i<n;i++)
    {
        scanf("%d \n",&a[i]);
    }
    maxi = max(a,n);
    mini = min(a,n);
    printf("\nMaximum element : %d",maxi);
    printf("\nMinimum element : %d",mini);
    getch();
}

int max(int a[],int n){
    int maxo=0,i=0;
    if(i<n){
        if(maxo < a[i]){
           maxo=a[i];
        }
        i++;
        max(a,n);
    }
    return maxo;
}

int min(int a[],int n){
    int mino=999,i=0;
    if(i<n){
        if(mino > a[i]){
            mino=a[i];
        }
        i++;
        min(a,n);
    }
    return mino;
}

Solution

  • Your functions max and min cause infinite recursion. That leads to stack overflow.

    You have:

    int max(int a[],int n){
       int maxo=0,i=0;
       if(i<n){
          if(maxo < a[i]){
             maxo=a[i];
          }
          i++;
          max(a,n);
       }
       return maxo;
    }
    

    The trouble with using recursive approach is that i is initialized to 0 in every recursive call. The fact that you are using i++ does not affect the value of i in the next recursive call. Similarly, the value of maxo is set to 0 in every recursive call.

    To make the recursive function to work, you'll need to pass i and maxo in the recursive function calls. Something like:

    int max(int a[],int n, int i, int maxo){
       if(i<n){
          if(maxo < a[i]){
             maxo=a[i];
          }
          return max(a, n, i+1, maxo);
       }
       return maxo;
    }
    

    and call the function with:

    maxi = max(a, n, 0, a[0]);
    

    Make similar changes to the definition of min and the call to min.