max is initialized to a very high value .. initialize max to 0;

int max = 0;

Here is the fixed code :

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main( void )
{
   int i  = 0;
   int a[11];

   int min = 0;
   int max = 0;

   srandom( (unsigned) time(NULL) );
   a[0]=random( ) % 100 ;
   min = a[0];

for (i=1;i<11;i++)
     {
       a[i]=random( ) % 100 ;


       printf("%d\n", a[i]);

       if (a[i] > max)
            {
          max = a[i];
            }
       if (a[i] < min)
            {
          min = a[i];
            }
    }
            printf("Min: %d\n", min);
            printf("Max: %d\n", max);

return 0;
}

Output:

Notra:Desktop Sukhvir$ ./try
82
91
33
8
60
48
60
6
59
62
60
Min: 6
Max: 91
Answer from sukhvir on Stack Overflow
Discussions

MInimum element in array ( C ) - Stack Overflow
Learn more about Collectives ... Bring the best of human thought and AI automation together at your work. Explore Stack Internal ... Save this question. Show activity on this post. I'm a newbie both here in stackoverflow and both in the world of programming. Today i was solving some exercise about recursion, and one of these asked to write a recursive function for finding minimum element of an array... More on stackoverflow.com
๐ŸŒ stackoverflow.com
Finding max and minimum values from an array in C - Stack Overflow
Learn more about Collectives ... Bring the best of human thought and AI automation together at your work. Explore Stack Internal ... Save this question. Show activity on this post. The purpose of this program is to read 10 double values in a one dimensional array and then search and print out the maximum and minimum ... More on stackoverflow.com
๐ŸŒ stackoverflow.com
C code to find max and min values: unexpected results
After the first loop, the value of i is 5, and the following is undefined, you are reading past the last element of the array numbers: max = numbers[i]; min = numbers[i]; To understand why, note that the loop for (i = 0; i < 5; i++) { /* loop body */ } is exactly equivalent to i = 0; while (i < 5) { /* loop body */ i++; } The while loop stops when the test is no longer true, that is, at i=5. Therefore, just after the loop, i=5. Then, you are reading a number in memory, just after the array. It's invalid, but the program simply reads the value there. It happens to be a large negative number. If you initialize min and max at the beginning of the function, but leave those two lines, the initial value is just overwritten with this invalid value. The simplest to fix this would be to initialize with numbers[0]. And the next for loop may start at i=1, since the 0 case is already taken into account. You have another problem: since average is an int, the exact average will be truncated. You may declare average as a double instead, and change the printf format specifier accordingly. More on reddit.com
๐ŸŒ r/cprogramming
13
7
January 12, 2025
algorithm - Min / Max function of 1D array in C / C++ - Code Review Stack Exchange
Due to software constraints, I cannot use the standard libraries, , , templates, inline, or Boost. I am also using standard C (ISO C99) such that array is not a reser... More on codereview.stackexchange.com
๐ŸŒ codereview.stackexchange.com
August 31, 2016
๐ŸŒ
Javatpoint
javatpoint.com โ€บ c-program-to-print-the-smallest-element-in-an-array
C program to print the smallest element in an array - Javatpoint
C program to print the smallest element in an array - In this program, we need to find out the smallest element present in the array. This can be achieved by maintaining a variable min which initially will hold the value of the first element. Loop through the array by comparing the value of ...
๐ŸŒ
Programming Simplified
programmingsimplified.com โ€บ c โ€บ source-code โ€บ c-program-find-minimum-element-in-array
C program to find minimum value in an array | Programming Simplified
If the minimum occurs two or more times in the array then the index at which it occurs first is printed or minimum value at the smallest index. You can modify the code to print the largest index at which the minimum occurs.
Top answer
1 of 3
1

It is a bad idea when a function depends on a global variable.

But in any case your function is incorrect and invokes undefined behavior.

In the first call of the function this if statement

Copyif (array[size] <= min) min = array[size];

trying to access memory outside the passed array because the valid range of indices is [0, size).

Also the array can contain all elements greater than the initial value of the global variable

Copyint min = 1000;

And the function may not be called a second time because the value of the variable min is unspecified.

The function should return the index of the minimal element in the array. In general the user can pass the second argument equal to 0. In this case again the function will invoke undefined behavior if you will try to return a non-existent element of an empty array.

The function can be declared and defined the following way

Copysize_t recursiveMinimum( const int a[], size_t n ) 
{
    if ( n < 2 )
    {
        return 0;
    }
    else
    {
        size_t min1 = recursiveMinimum( a, n / 2 );
        size_t min2 = recursiveMinimum( a + n / 2, n - n / 2 ) + n / 2;

        return a[min2] < a[min1] ? min2 : min1;
    }
}

Here is a demonstration program

Copy#include <stdio.h>

size_t recursiveMinimum( const int a[], size_t n )
{
    if (n < 2)
    {
        return 0;
    }
    else
    {
        size_t min1 = recursiveMinimum( a, n / 2 );
        size_t min2 = recursiveMinimum( a + n / 2, n - n / 2 ) + n / 2;

        return a[min2] < a[min1] ? min2 : min1;
    }
}

int main( void )
{
    int a[] = { 55, 5, 1, 27, 95, 2 };
    const size_t N = sizeof( a ) / sizeof( *a );

    size_t min = recursiveMinimum( a, N );

    printf( "\nMinimum element of this array is: %d at the position %zu\n",
            a[min], min );
}

The program output is

CopyMinimum element of this array is: 1 at the position 2

Pay attention to that the first parameter has the qualifier const because the passed array is not being changed within the function. And to decrease the number of recursive calls the function calls itself for two halves of the array.

2 of 3
0

Recursion works by reducing the size at the call to the next iteration and comparing the result of the call with the current value and return the lower of the 2.

As recursion stop you can simply return the first element

Copyint recursiveMinimum(int array[], size_t size) {
  if (size == 1) return array[0];
  int min_of_rest = recursiveMinimum(array, size - 1);
  if (array[size - 1] <= min_of_rest) return array[size - 1];
  return min_of_rest;
}

Full example: https://godbolt.org/z/sjnh8sYz3

๐ŸŒ
W3Schools
w3schools.in โ€บ c-programming โ€บ examples โ€บ find-minimum-element-in-array
C Program to Find Minimum Element in Array - W3Schools
#include <stdio.h> int main() { int array[100], *minimum, size, c, location = 1; printf("Enter the number of elements in array\n"); scanf("%d",&size); printf("Enter %d integers\n", size); for ( c = 0 ; c < size ; c++ ) scanf("%d", &array[c]); minimum = array; *minimum = *array; for ( c = 1 ; c < size ; c++ ) { if ( *(array+c) < *minimum ) { *minimum = *(array+c); location = c+1; } } printf("Minimum element found at location %d and it's value is %d.\n", location, *minimum); return 0; }
๐ŸŒ
Learn Java
javatutoring.com โ€บ c-program-find-maximum-minimum-element-in-array
C Program To Find Maximum & Minimum Element In Array | C Prorams
February 25, 2026 - Thus, doing the same using multiple methods in C programming is as follows: Read the entered array size and store that value into the variable n. 2) Read the entered elements using scanf and store the entered array elements into the array using ...
Find elsewhere
๐ŸŒ
Studyfame
studyfame.com โ€บ c-program โ€บ c-program-to-find-maximum-and-minimum-number-in-an-array
c program to find maximum and minimum number in an array
#include<stdio.h> int main() { int a[50],i,j,max,min,n; printf("\nenter the size of array:"); scanf("%d",&n); printf("enter element in array:"); for(i=0;i<n;i++) { scanf("%d",&a[i]); } /* Assume first array element as maximum and minimum */ max=a[0]; min=a[0]; for(i=0;i<n;i++) { if(a[i]>max) { max=a[i]; } if(a[i]<min) { min=a[i]; } } printf("largest number: %d",max); printf("\nsmallest number: %d",min); return 0; } enter the size of array:6 enter element in array:1 4 6 3 2 5 largest number: 6 smallest number: 1 ยท Take the size of an array from a user and stored it in variable n. Take n element from the user and store it in an array a. ... iterate the for loop from 1 to n. inside the loop check the a[i]> max.
Top answer
1 of 8
2

scanf("%lf",&num); will invoke undefined behavior because double(*)[10] is passed where double* is expected.

You should read to each elements if you want to use an array. Note that array index in C starts from 0, not 1. You also should check if reading is successful.

Copy#include<stdio.h>

// main program 
int main(void){
    int i;
    double num[10];
    for (i=1;i<=10;i++){
        printf("Enter a number: ");
        if (scanf("%lf",&num[i - 1]) != 1){
            puts("read error");
            return 1;
        }
    }
    // calculate max and minimum values and print them
    return 0;
}

or this code uses what seems better for range of i.

Copy#include<stdio.h>

// main program 
int main(void){
    int i;
    double num[10];
    for (i=0;i<10;i++){
        printf("Enter a number: ");
        if (scanf("%lf",&num[i]) != 1){
            puts("read error");
            return 1;
        }
    }
    // calculate max and minimum values and print them
    return 0;
}
2 of 8
2

If, in addition to the other answers, you intend to write/call a function to find both the max and min values in your array of doubles, your first challenge is overcoming the axiom that only a single value (or pointer) can be returned by a function in C. There are several options available to determine the max and min in a function (or functions).

The first, and obvious, alternative is to write both a max and min function and call each. (but that would require iterating over your array twice -- that would be less than optimal). Your next option is to pass a separate array (of at least 2 double values) to store your max and min values in and either update the values or return a pointer to that array

(passing the array will automatically make values stored in the maxmin array available back in your calling function (main() in your case), but to immediately use the values in same call, you can return the pointer to the max/min array for convenience. You can also return NULL on error to indicate failure)

Or, since there are only 2 values needed, you can pass individual pointers to max and min as parameters and update the values pointed to by each within your function. Choosing some return type to indicate success/failure is also a good idea. int in this case is as efficient as any other (better from a numeric conversion standpoint)

With that in mind a simple maxmin function taking a pointer to your array of double values, pointers to each max and min and finally the number of values in the array could be written like:

Copy/** find the max and min in array of 'n' doubles `ad`.
 *  update 'max' and 'min' pointers so values are available back
 *  in calling function.
 */
int maxmin_dbl (double *ad, double *max, double *min, size_t n)
{
    if (!ad || !max || !min) return 0;  /* validate parameters */

    *max = (double)LLONG_MIN;   /* initialize max/min to sufficiently */
    *min = (double)LLONG_MAX;   /* large negative/positive values.    */

    size_t i;
    for (i = 0; i < n; i++) {
        if (ad[i] > *max) *max = ad[i];  /* test for new max */
        if (ad[i] < *min) *min = ad[i];  /* test for new min */
    }

    return 1;
}

(note: if your data values are outside the range of LLONG_MIN and LLONG_MAX, you will need to adjust your initializations accordingly)

A short example program reading values from the filename given as the first argument (or from stdin by default) and writing the array values and maximum and minimum to stdout could be written as:

Copy#include <stdio.h>
#include <stdlib.h>
#include <limits.h>

enum { MAXD = 10 };  /* constant for no. of values */

int maxmin_dbl (double *ad, double *max, double *min, size_t n);

int main (int argc, char **argv) {

    size_t i, n;
    double max, min, tmp, ad[MAXD] = {0.0};
    FILE *fp = argc > 1 ? fopen (argv[1], "r") : stdin;

    if (!fp) {  /* validate file open for reading */
        fprintf (stderr, "error: file open failed '%s'.\n", argv[1]);
        return 1;
    }

    /* read double values from fp until at most 10 values read */
    for (n = 0; n < MAXD && fscanf (fp, " %lf", &tmp) == 1; n++)
        ad[n] = tmp;

    if (fp != stdin) fclose (fp);     /* close file if not stdin */

    printf ("\narray values:\n\n");   /* output the values read  */
    for (i = 0; i < n; i++)
        printf ("  ad[%2zu] : %13.2lf\n", i, ad[i]);

    if (maxmin_dbl (ad, &max, &min, n))  /* get max/min from array */
        printf ("\n maximum : %.2lf\n minimum : %.2lf\n\n", max, min);
    else {
        fprintf (stderr, "error: maxmin_dbl failed.\n");
        return 1;
    }

    return 0;
}

/** find the max and min in array of 'n' doubles `ad`.
 *  update 'max' and 'min' pointers so values are available back
 *  in calling function.
 */
int maxmin_dbl (double *ad, double *max, double *min, size_t n)
{
    if (!ad || !max || !min) return 0;  /* validate parameters */

    *max = (double)LLONG_MIN;   /* initialize max/min to sufficiently */
    *min = (double)LLONG_MAX;   /* large negative/positive values.    */

    size_t i;
    for (i = 0; i < n; i++) {
        if (ad[i] > *max) *max = ad[i];  /* test for new max */
        if (ad[i] < *min) *min = ad[i];  /* test for new min */
    }

    return 1;
}

Example Use/Output

Copy$ ./bin/arrdbl_maxmin <../dat/10int_nl.txt

array values:

  ad[ 0] :       8572.00
  ad[ 1] :      -2213.00
  ad[ 2] :       6434.00
  ad[ 3] :      16330.00
  ad[ 4] :       3034.00
  ad[ 5] :      12346.00
  ad[ 6] :       4855.00
  ad[ 7] :      16985.00
  ad[ 8] :      11250.00
  ad[ 9] :       1495.00

 maximum : 16985.00
 minimum : -2213.00

Look over all the answers, those that directly address your error, and then let us know if you have any further questions.

๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ c language โ€บ c-program-to-find-minimum-value-in-array
C Program to Find Minimum Value in Array - GeeksforGeeks
July 23, 2025 - The function reduces the search size by comparing the last element with the minimum of the remaining elements and recursively processing the rest of the array.
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ c language โ€บ c-program-to-find-the-maximum-and-minimum-element-of-the-array
C Program to Find the Maximum and Minimum Element in the Array - GeeksforGeeks
July 12, 2025 - The simplest method to find the maximum and minimum element of the array is iterates through the array and compare each element with the assumed minimum and maximum and update them if the current element is smaller or larger respectively.
๐ŸŒ
Reddit
reddit.com โ€บ r/cprogramming โ€บ c code to find max and min values: unexpected results
r/cprogramming on Reddit: C code to find max and min values: unexpected results
January 12, 2025 -

Hi everyone,

I'm trying to find the maximum and minimum values in a C array, but I'm running into a problem. My code calculates the maximum value correctly, but the minimum value is always a very large negative number, even when all the values in the array are positive.

I've tried initializing the min variable to a large positive number, but it doesn't seem to help.

Here's my code:

#include <stdio.h>

int main(void)
{
    int i, sum = 0;
    int numbers [5];
    int min, max, average;
    
    printf("enter 5 numbers:\n");
    
    for (i = 0; i < 5; i++)
    {
        scanf("%d", &numbers[i]);
        sum += numbers[i];
    }
    
    max = numbers[i];
    min = numbers[i];
    
    for (i = 0; i < 5 ; i++)
    {
        if (numbers[i] > max)
        {
            max = numbers[i];
        }
        if (numbers[i] < min)
        {
            min = numbers[i];
        }
        
    }
    
    average = (double)sum/5;
    
    printf("Average is %d and sum is %d\n", average, sum);
    printf("Max number is %d and the min number is %d\n", max, min);
    
}

Can anyone help me figure out what's going wrong?

Thanks!

๐ŸŒ
Codeforwin
codeforwin.org โ€บ home โ€บ c program to find maximum and minimum element in array
C program to find maximum and minimum element in array - Codeforwin
July 20, 2025 - Run loop from first to last array element i.e. 0 to size - 1. Loop structure should look like for(i=0; i<size; i++). Inside loop for each array element check for maximum and minimum.
Top answer
1 of 3
20

It's not quite the best. There's some things IMHO that is hindering its performance and usefulness.

There's no point in declaring val as a static variable. In fact, you've killed any chance of it being usable in multi-threaded programs.

The body of the loop is performing an assignment in every single iteration when it doesn't need to. If you want it to be its best, you should only be doing so when it is required.

Your overall structure is fine, assuming we can expect well-formed inputs where array is nonempty and size is positive, I'd just change it so it's more like this:

double min(const double *arr, size_t length) {
    // returns the minimum value of array
    size_t i;
    double minimum = arr[0];
    for (i = 1; i < length; ++i) {
        if (minimum > arr[i]) {
            minimum = arr[i];
        }
    }
    return minimum;
}
2 of 3
6

You can use SSE2/SSE3 minps / pminsd or relevant instruction set for your processor/architectoure since it is supported directly in GCC / MASM / TASM (In case MASM or TASM is not supported such SSE2/SSE3 instruction set there are also the .inc files to create macros simulating instruction sets on the web for MASM), create .OBJ file by your favorite linker then link it as usual and use in you favorite IDE. You will get from 4x to 16x performance boost compared to the traditional "classic" algorithm. It depend on data size (old compilers treats double not in IEEE format, bout like float in several configurations, on 16x systems, particularly, double means 32 bit data structure, not 64 bit data structure, in modern languages it is correlated to "double" and "long double" data structures, respectively)

The idea is simple: if you have k elements, [k=4n+p, 4>p=>0], complete it with n-p elements or just load last 4 doubles resetting to 0 last p elements, so you can fast evaluate n candidates. evaluate candidates n times comparing to the accumulator, you will get a minimum.

If your processor supports SSE5 or is a brand new, most likely you also will be using one of the HD instructions, which really handy, because it can find maximum (not minimum yet) in array of double values.

Sample of using SSE to calculate peak values of a float array:

#include <xmmintrin.h>

double min(double* array, int size) { 
    // returns the minimum value of array 
    int i; 
    double val = array[0]; 
    for (i = 1; i < size; ++i) { 
        if (val > array[i]) { 
            val = array[i]; 
        } 
    } 
    return val; 
} 

#define ARRAY_SIZE 16

float m_fArray[ARRAY_SIZE];

void x86_sse_find_peaks(float *buf, unsigned nframes, float *min, float *max)
{
    __m128 current_max, current_min, work;

    // Load max and min values into all four slots of the XMM registers
    current_min = _mm_set1_ps(*min);
    current_max = _mm_set1_ps(*max);

    // Work input until "buf" reaches 16 byte alignment
    while ( ((unsigned long)buf) % 16 != 0 && nframes > 0) {

        // Load the next float into the work buffer
        work = _mm_set1_ps(*buf);

        current_min = _mm_min_ps(current_min, work);
        current_max = _mm_max_ps(current_max, work);

        buf++;
        nframes--;
    }

    // use 64 byte prefetch for quadruple quads
    while (nframes >= 16) {
        //__builtin_prefetch(buf+64,0,0); // for GCC 4.3.2+

        work = _mm_load_ps(buf);
        current_min = _mm_min_ps(current_min, work);
        current_max = _mm_max_ps(current_max, work);
        buf+=4;
        work = _mm_load_ps(buf);
        current_min = _mm_min_ps(current_min, work);
        current_max = _mm_max_ps(current_max, work);
        buf+=4;
        work = _mm_load_ps(buf);
        current_min = _mm_min_ps(current_min, work);
        current_max = _mm_max_ps(current_max, work);
        buf+=4;
        work = _mm_load_ps(buf);
        current_min = _mm_min_ps(current_min, work);
        current_max = _mm_max_ps(current_max, work);
        buf+=4;
        nframes-=16;
    }

    // work through aligned buffers
    while (nframes >= 4) {

        work = _mm_load_ps(buf);

        current_min = _mm_min_ps(current_min, work);
        current_max = _mm_max_ps(current_max, work);

        buf+=4;
        nframes-=4;
    }

    // work through the rest < 4 samples
    while ( nframes > 0) {

        // Load the next float into the work buffer
        work = _mm_set1_ps(*buf);

        current_min = _mm_min_ps(current_min, work);
        current_max = _mm_max_ps(current_max, work);

        buf++;
        nframes--;
    }

    // Find min & max value in current_max through shuffle tricks

    work = current_min;
    work = _mm_shuffle_ps(work, work, _MM_SHUFFLE(2, 3, 0, 1));
    work = _mm_min_ps (work, current_min);
    current_min = work;
    work = _mm_shuffle_ps(work, work, _MM_SHUFFLE(1, 0, 3, 2));
    work = _mm_min_ps (work, current_min);

    _mm_store_ss(min, work);

    work = current_max;
    work = _mm_shuffle_ps(work, work, _MM_SHUFFLE(2, 3, 0, 1));
    work = _mm_max_ps (work, current_max);
    current_max = work;
    work = _mm_shuffle_ps(work, work, _MM_SHUFFLE(1, 0, 3, 2));
    work = _mm_max_ps (work, current_max);

    _mm_store_ss(max, work);
}

int _tmain(int argc, _TCHAR* argv[])
{
    float   min = FLT_MAX;
    float   max = FLT_MIN;

    m_fArray[0] = 0;
    m_fArray[1] = 1;
    m_fArray[2] = 2;
    m_fArray[3] = 3;
    m_fArray[4] = 4;
    m_fArray[5] = 3;
    m_fArray[6] = 2;
    m_fArray[7] = 1;
    m_fArray[8] = -1;
    m_fArray[9] = -2;
    m_fArray[10] = -3;
    m_fArray[11] = -4;
    m_fArray[12] = -5;
    m_fArray[13] = -6;
    m_fArray[14] = -7;
    m_fArray[15] = -8;

    x86_sse_find_peaks(m_fArray, ARRAY_SIZE, &min, &max);

    printf("value = %.2f, max = %.2f\n", min, max); // output is: value = -8.00, max = 4.00
    return 0;
}
๐ŸŒ
C For Dummies
c-for-dummies.com โ€บ blog
Min and Max | C For Dummies Blog
September 1, 2013 - array_min() This function returns the lowest (minimum) value stored in the array.
๐ŸŒ
Quora
quora.com โ€บ How-do-you-find-a-minimum-value-from-an-array-in-C
How to find a minimum value from an array in C++ - Quora
IBM FlashSystem from CDW works in hybrid, on-prem, and cloud setups with advanced security throughout. ... Assign a[i] to min. At last you would get minium of array .
๐ŸŒ
Quora
quora.com โ€บ How-do-you-write-a-C-program-to-find-the-maximum-and-minimum-value-in-an-array-of-n-elements
How to write a C program to find the maximum and minimum value in an array of n elements - Quora
Answer (1 of 9): [code]#include int main(){ int n; double arr[100]; //define array number range printf(" please enter how many number :"); scanf("%d",&n); //-------------Enter value in array------- for(int i=0;i
๐ŸŒ
Jagiroad College
jagiroadcollegelive.co.in โ€บ attendence โ€บ classnotes โ€บ files โ€บ 1589995691.pdf pdf
Program to calculate average of array in C #include <stdio.h> int main() {
#include <conio.h> int main() { int a[1000],i,n,min,max; printf("Enter size of the array : "); scanf("%d",&n); printf("Enter elements in array : "); for(i=0; i<n; i++) { scanf("%d",&a[i]); } min=max=a[0]; for(i=1; i<n; i++) { if(min>a[i]) min=a[i]; if(max<a[i]) max=a[i]; } printf("minimum of array is : %d",min); printf("\nmaximum of array is : %d",max); return 0; }r elements in array: 1 ยท
๐ŸŒ
GitHub
github.com โ€บ kkenth007 โ€บ C-Language-Learn-C-programming โ€บ blob โ€บ master โ€บ max,min,array.c
C-Language-Learn-C-programming/max,min,array.c at master ยท kkenth007/C-Language-Learn-C-programming
int size,i,max,min; printf("\n Enter array size : "); scanf("%d",&size); int array[size]; printf(" Enter array element\n\n"); for (i=0;i<size;i++) { printf(" Number %d : ", i+1); scanf("%i",&array[i]); } max=array[0]; for (i=0;i<size;i++) { (array[i]>max)?
Author ย  kkenth007
๐ŸŒ
w3resource
w3resource.com โ€บ c-programming-exercises โ€บ function โ€บ c-function-exercise-12.php
C Program: Returns an array of maximum, minimum values
October 24, 2025 - The function finds the minimum and maximum elements of the array arra1 by iterating through all elements of the array and keeping track of the minimum and maximum elements seen so far.