C Program to Find Minimum and Maximum Number in an Array

In this post, we will write a C program to find the minimum and maximum numbers in an array.

C Program to Find Minimum and Maximum Number in an Array

In this program, we will make a function return two values, the maximum and minimum values, and store them in another array. Thereafter, the array containing the maximum and minimum values will be returned from the function.

C functions cannot return more than one value. But what if you want a function to return more than one value? The solution is to store the values to be returned in an array and make the function return the array instead.

Let's create a file named findminmax.c and add the following source code to it:

# include <stdio.h>

#define max 10

int *maxmin(int ar[], int v);

void main()
{
  	int  arr[max];
	int n,i, *p;
  	printf("How many values? ");
  	scanf("%d",&n);
  	printf("Enter %d values\n", n);
  	for(i=0;i<n;i++)
    		scanf("%d",&arr[i]);
  	p=maxmin(arr,n);
	printf("Minimum value is %d\n",*p++);
	printf("Maximum value is %d\n",*p);
}

int *maxmin(int ar[], int v)
{
 	int i;
	static int mm[2];
	mm[0]=ar[0];
	mm[1]=ar[0];
	for (i=1;i<v;i++)
	{
		if(mm[0] > ar[i])
    			mm[0]=ar[i];
		if(mm[1]< ar[i])
  			mm[1]= ar[i];
	}
	return mm;
}

To compile and run the above C program, you can use C Programs Compiler Online tool.

Output:

How many values? 5
Enter 5 values
10
20
30
40
50
Minimum value is 10
Maximum value is 50





Comments