-2

Below is my code for finding the minimum and maximum value from an array. Can anyone explain why I am getting 0 as the output for minimum element? What can be the reason behind it?

I am getting the maximum value among the elements of array as desired.

#include<stdio.h>
#define N 3

int a[N],min,max, max1,min1;
void minmax(int m,int n);

void minmax(int m, int n){
    if(m==n){
        max=min=a[m];
        return;
    }

    if(m == n-1){
        if(a[m]>a[n]){
            max= a[m];
            min = a[n];

        }
        else{
            max= a[n];
            min = a[m];
        }
    }
    else{

        int mid = (m+n)/2;

        minmax(1,mid);
        max1=max;
        min1=min;
        minmax(mid+1,n);
    }

    if(max1>max){
        max= max1;
    }

    if(min1<min){
        min=min1;
    }


}

int main(){

    int i,j,k;
    printf("Enter array\n");
    for(i=1;i<=N;i++)   //input
        scanf("%d",&a[i]);

    minmax(1,N);

    printf("%d %d",max,min);

}
Nisse Engström
  • 4,738
  • 23
  • 27
  • 42

1 Answers1

0
  • In your minmax function, you return from the call when m==n
  • But do you know the values of m and n when it reaches that? One of the values include m=n=0.

Firstly, your for loop takes an array from index=1 till N. If you do so, make sure you make the necessary changes in minmaxfunction also.

So, the simplest fix (just saw mentioned in comments also) is:

Change for(i=1;i<=N;i++) to for(i=0;i<N;i++)

Rahul Bharadwaj
  • 2,555
  • 2
  • 18
  • 29