C program to find the maximum and minimum element of the array
Last Updated :
17 Apr, 2023
Given an array arr[] of N integers, the task is to write the C program to find the maximum and minimum element of the given array iteratively and recursively. Examples:
Input: arr[] = {1, 2, 4, -1} Output: The minimum element is -1 The maximum element is 4 Input: arr[] = {-1, -1, -1, -1} Output: The minimum element is -1 The maximum element is -1
Approach:
- Let maxE and minE be the variable to store the minimum and maximum element of the array.
- Initialise minE as INT_MAX and maxE as INT_MIN.
- Traverse the given array arr[].
- If the current element is smaller than minE, then update the minE as current element.
- If the current element is greater than maxE, then update the maxE as current element.
- Repeat the above two steps for the element in the array.
Iterative approach
Below is the implementation of the Iterative approach:
C
#include <limits.h>
#include <stdio.h>
void findMinimumMaximum( int arr[], int N)
{
int i;
int minE = INT_MAX, maxE = INT_MIN;
for (i = 0; i < N; i++) {
if (arr[i] < minE) {
minE = arr[i];
}
if (arr[i] > maxE) {
maxE = arr[i];
}
}
printf ( "The minimum element is %d" , minE);
printf ( "\n" );
printf ( "The maximum element is %d" , maxE);
return ;
}
int main()
{
int arr[] = { 1, 2, 4, -1 };
int N = sizeof (arr) / sizeof (arr[0]);
findMinimumMaximum(arr, N);
return 0;
}
|
Output:
The minimum element is -1
The maximum element is 4
Recursive approach
Below is the implementation of the Recursive approach:
C
#include <limits.h>
#include <stdio.h>
void recursiveMinMax( int arr[], int N, int * minE, int * maxE)
{
if (N < 0) {
return ;
}
if (arr[N] < *minE) {
*minE = arr[N];
}
if (arr[N] > *maxE) {
*maxE = arr[N];
}
recursiveMinMax(arr, N - 1, minE, maxE);
}
void findMinimumMaximum( int arr[], int N)
{
int i;
int minE = INT_MAX, maxE = INT_MIN;
recursiveMinMax(arr, N - 1, &minE, &maxE);
printf ( "The minimum element is %d" , minE);
printf ( "\n" );
printf ( "The maximum element is %d" , maxE);
return ;
}
int main()
{
int arr[] = { 1, 2, 4, -1 };
int N = sizeof (arr) / sizeof (arr[0]);
findMinimumMaximum(arr, N);
return 0;
}
|
Time Complexity: O(N), where N is the number of element in the given array.
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...