Write a C program to input elements in an array from user, find maximum and minimum element in array. C program to find biggest and smallest elements in an array. Logic to find maximum and minimum element in array in C programming.
Example
Input
Input array elements: 10, 50, 12, 16, 2
Output
Maximum = 50 Minimum = 2
Required knowledge
Basic Input Output, If else, For loop, Array
Logic to find maximum and minimum element in array
Below is the step by step descriptive logic to find maximum or minimum in array.
- Input size and element in array, store it in some variable say
size
andarr
. - Declare two variables
max
andmin
to store maximum and minimum. Assume first array element as maximum and minimum both, saymax = arr[0]
andmin = arr[0]
. - Iterate through array to find maximum and minimum element in array. Run loop from first to last array element i.e. 0 to
size - 1
. Loop structure should look likefor(i=0; i<size; i++)
. - Inside loop for each array element check for maximum and minimum. Assign current array element to
max
, if(arr[i] > max)
. Assign current array element tomin
if it is less thanmin
i.e. performmin = arr[i]
if(arr[i] < min)
.
Program to find maximum and minimum element in array
/**
* C program to find maximum and minimum element in array
*/
#include <stdio.h>
#define MAX_SIZE 100 // Maximum array size
int main()
{
int arr[MAX_SIZE];
int i, max, min, size;
/* Input size of the array */
printf("Enter size of the array: ");
scanf("%d", &size);
/* Input array elements */
printf("Enter elements in the array: ");
for(i=0; i<size; i++)
{
scanf("%d", &arr[i]);
}
/* Assume first element as maximum and minimum */
max = arr[0];
min = arr[0];
/*
* Find maximum and minimum in all array elements.
*/
for(i=1; i<size; i++)
{
/* If current element is greater than max */
if(arr[i] > max)
{
max = arr[i];
}
/* If current element is smaller than min */
if(arr[i] < min)
{
min = arr[i];
}
}
/* Print maximum and minimum element */
printf("Maximum element = %d\n", max);
printf("Minimum element = %d", min);
return 0;
}
Add a plus to your skills, learn this program using recursive approach.
Output
Enter size of the array: 10 Enter elements in the array: -10 10 0 20 -2 50 100 20 -1 10 Maximum element = 100 Minimum element = -10
Happy coding 😉
Recommended posts
- Array and Matrix programming exercises index.
- C program to find maximum between two numbers using switch case.
- C program to find maximum between two numbers using conditional/ternary operator.
- C program to find second largest element in an array.
- C program to find maximum between three numbers.
- C program to count total number of duplicate elements in an array.