Write a program that determines the largest and the smallest value in an array of integers A.
Next, display the value, the number of appearance and the position of the maximum and minimum values.
If the array contains several maxima or minima, the program will retain the position of the first maximum or minimum encountered.
Example:
- T={3, 8, 9, 5, 0 , -6, 9, -5}
- Min = -6 , index= 5 , nb of appearance=1
- Max= 9, index = 2, nb of appearance=2
Difficulty level
Video recording
This exercise is mostly suitable for students
#include<stdio.h>
#include<math.h>
#include<conio.h>
#define SIZE 1000
void main()
{
int A[SIZE];
int dim;
int i;
int min, max;
// max = A[0]; wrong here
int imin, imax;
int countmin, countmax;
do {
printf("Enter the dimension: ");
scanf("%d", &dim);
} while (dim <= 0 || dim > SIZE);
printf("**Reading first vector**\n");
for (i = 0; i<dim; i++)
{
printf("Enter A[%d]=", i);
scanf("%d", &A[i]);
}
min = max = A[0];
imin = imax = 0;
countmax = countmin = 1;
for (i = 1; i < dim; i++) // we skipped checking for i=0
{
if (A[i] > max)
{
max = A[i];
imax = i;
countmax = 1;
}
else if (A[i] == max)
{
countmax++;
}
if (A[i] < min)
{
min = A[i];
imin = i;
countmin = 1;
}
else
if (A[i] == min)
{
countmin++;
}
}
printf("Min=%d, Imin=%d, Count=%d\n", min, imin, countmin);
printf("Max=%d, Imax=%d, Count=%d\n", max, imax, countmax);
getch();
}
Back to the list of exercises
Looking for a more challenging exercise, try this one !!
Implementation of a deque using a doubly-linked list