Home > front end >  Isnt there any predefined funtion in C to find the minimum or maximum element from a given array?
Isnt there any predefined funtion in C to find the minimum or maximum element from a given array?

Time:09-21

I've an array. int a[6] = {3, 4, 1, 2, 5, 6} and I want to find the minimum and maximum element by using per-defined C function,if there is any? Please help

CodePudding user response:

No there is no standard C function. But You can do this yourself

int max = arr[0];
for (i = 1; i < n; i  )
    if (arr[i] > max)
        max = arr[i];

Whether it's big or small is obvious from the comparison inside the if. if >, is large. if <, is small

CodePudding user response:

No, there isn't a minmax function in the standard library, but you could create one yourself.

Example:

#include <limits.h>
#include <stddef.h>
#include <stdio.h>

// a struct to hold the min and max result
typedef struct {
    int min;
    int max;
} mm;

// a function to find the min and max values
mm minmax(const int *arr, size_t len) {

    mm res = {INT_MAX, INT_MIN}; // start with min = INT_MAX, max = INT_MIN

    for(const int *end = arr   len; arr != end;   arr) {
        if(*arr < res.min) res.min = *arr;
        if(*arr > res.max) res.max = *arr;
    }

    return res;
}

int main() {
    int a[6] = {3, 4, 1, 2, 5, 6};
    mm res = minmax(a, sizeof a / sizeof *a);
    printf("min: %d  max: %d\n", res.min, res.max);
}

CodePudding user response:

C99 contains math.h This has functions - fmin, fmax, fminl, fmaxl, fmaxf, fminf

#include <math.h>
double fmin( double x, double y );
float fminf( float x, float y );
long double fminl( long double x , long double y );

The fmin() functions return the value of the lesser argument.

#include <math.h>
double fmax( double x, double y );
float fmaxf( float x, float y );
long double fmaxl( long double x , long double y );

The fmax() functions return the value of the greater argument.

So, for the answer -

float max=0;
for (i = 0; i < n; i  )
        max = fmaxf (max, arr[i]);
  • Related