Write a program that reads an array and finds the second maximum element in the array.


Difficulty level
This exercise is mostly suitable for students
#include <stdio.h>
#include <conio.h>
#define NB_ELEMENT 10

void main()
{
	int size;
	int A[NB_ELEMENT];
	int i, j;
	int pmax1, pmax2;


	do{
		printf("Enter the number of elements: ");
		scanf("%d", &size);
	}while(size<=0 || size > NB_ELEMENT);
	
	for (i = 0; i < size ; i++) {
		printf("Enter Element %d: ", i );
		scanf("%d", &A[i]);
	}

 	pmax1=0;
	pmax2=-1;
	for(i=1; i<size ;i++)
	{
		if(A[i]>A[pmax1])
		{
			pmax2=pmax1;
			pmax1=i;
		}
		else
			if(pmax2!=-1 && A[i]>A[pmax2])
				pmax2=i;
	}

	printf("The second maximum is at position %d, its value is equal to %d.\n", pmax2,(pmax2>=0?A[pmax2]:-1));	
	getch();
}

Back to the list of exercises
Looking for a more challenging exercise, try this one !!
Average value and second distinct maximum