Search code examples
arrayscrecursionfunction-definition

Recursive function to get the minimum maximum and sum of an array of integers


Hello I'm struggling a little bit, I can't really figure out how to initialize my *min *max and *sum variables so that it doesn't keep reinitializing in the loop

I did this and I'd like to get help regarding what changes I should make

void min_max_sum_rec(int arr[],int length,int *min,int *max,int *sum){

    if(length==1){
        return;
    }
    else{
        if(arr[0]<*min){
            *min = arr[0];
        }
        if(arr[0]>*max){
            *max = arr[0];
        }
        sum+=arr[0];
    }
    min_max_sum_rec(arr+1,length-1,min,max,sum);
}

for reference my professor did this:

void min_max_sum(int arr[],int length,int *min,int *max,int *sum){

    if(length== 1){
        *min=*max=*sum=*arr;
         return;
    }
    min_max_sum(arr+1,length-1,min,max,sum);

    *sum+=arr[0];
    *min = (*min<arr[0]?*min:arr[0]);
    *max = (*max>arr[0]?*max:arr[0]);
}

but I don't really understand since *min *sum and *max are not initialized and also can't understand the if statement.

Wouldn't it make it so that when we only have an array with one integer *max *min and *sum would have the same value so all we did before would be meaningless ?


Solution

  • I assume this is your professors code:

    void min_max_sum(int arr[],int length,int *min,int *max,int *sum){
    
        if(length== 1){
            *min=*max=*sum=*arr;
             return;
        }
        min_max_sum(arr+1,length-1,min,max,sum);
    
        *sum+=arr[0];
        *min = (*min<arr[0]?*min:arr[0]);
        *max = (*max>arr[0]?*max:arr[0]);
    }
    

    and it's fine. But the documentation must clearly state that the function is only allowed to be called with values of n being greater than zero.

    You ask:

    Wouldn't it make it so that when we only have an array with one integer *max *min and *sum would have the same value so all we did before would be meaningless ?

    Well, no... because we did not do anything before!

    Notice that all the comparision for max/min and the sum calculation is after the recursion ends.

    In other words - the code keeps making recursive calls with shorter and shorter array until there is only one element. The value of that element (which is the last element of the original array) is then used for initializing max/min/sum. As the recursive calls return it's checked whether a previous element is larger/smaller in order to update max/min and also updates sum.

    It's a nice and simple implementation but....

    This task should never be solved using recursion

    You should ask your professor for an assignment where recursion actually makes sense.