This is little tricky, but not difficult. easiest way to do this is to sort the array and then find the answer. But that not expected out of you.
The algorithm here is take thefirst element as the max and second max. Then loop through all elements
- If the number is larger than max then make it max, and make old max to second max.
- Else if it is more than second max then make it the second max.
- In all other cases drop that number
/*
** Write a program for finding the max and second max
** of an array of given size */
#define SIZE 10
int main(void)
{
int array[SIZE] = {10, 5, 16, 2, 1, 2, 3, 18, 21, 4};
int i, max, sec_max;
max = sec_max = array[0];
for(i=0; i< SIZE; i++)
{
if(array[i] > max) {
sec_max = max;
max = array[i];
}
else if(array[i] > sec_max)
sec_max = array[i];
}
printf("max = %d, sec max = %d", max, sec_max);
}
No comments:
Post a Comment