What I want: Suppose there is an array of some size. First, I want to find the maximum element in the array, and if there is more than one element with the same maximum value, then I want to store each of the indices of the maximum element without altering the ordering of the elements in the array.
Example: Let's say there are two classes: class A & class B. In an exam, each student of class A scored differently from the others, so we could easily find the maximum score and who scored it in the said exam. However, in the same exam, two students from class B scored the maximum score. Now, we have to identify those two students (with the help of their roll numbers, say) and the score they scored. I don't know how to do that!
What I know: I know how to code a C program to find the maximum value in an array with its index value. But, if there are multiple elements with the same max value in different positions in an array, then I think I would need a new array to store the indices of the max element. Once I achieve that, I could easily find the max value with the aid of any of the stored indices.
My attempt:
#include<stdio.h>
int main(void)
{
size_t arr[5] = {2,8,10,7,10};
size_t i,j,max = arr[0];
size_t indices[5]={0};
for(j = 0;j < 5; ++j)
{
for(i = 0;i < 5; ++i)
{
if(arr[i] >= max)
indices[j] = i;
}
printf("Max Value: %zu ----> Position: %zu\n",arr[indices[j]],indices[j]+1);
}
return 0;
}
The output it generates:
Max Value: 10 ----> Position: 5
Max Value: 10 ----> Position: 5
Max Value: 10 ----> Position: 5
Max Value: 10 ----> Position: 5
Max Value: 10 ----> Position: 5
(I knew that it won't work, and it didn't as well. The index 3 is getting lost in the process!)
The desired output should read something like this:
Max Value: 10 ----> Position: 3
Max Value: 10 ----> Position: 5
Please suggest how I can code a C program that can perform the desired task.