Question & Solution #1
Question:
Take input from the user in an array and print the second maximum value from the entered input.
Source:
The Knowledge Network Club
#include <stdio.h>
int main() {
// Declare variables
int i, elements;
// Input the number of elements in the array
printf("Enter the number of elements in the array: ");
scanf("%d", &elements);
// Declare an array to store the elements
int input[elements];
// Input unique elements of the array
printf("Enter the unique elements of the array: ");
for (i = 0; i < elements; i++) {
scanf("%d", &input[i]);
}
// Find the maximum element and its index
int max1 = input[0], index1 = 0;
for (i = 1; i < elements; i++) {
if (input[i] > max1) {
max1 = input[i];
index1 = i;
}
}
printf("\nMax element is: %d at index %d", max1, index1);
// Initialize second maximum element and its index
int max2 = 0, index2 = 0;
// Check max2 with the first non-maximum element's value
for (i = 0; i < elements; i++) {
if (i == index1) {
continue; // Skip the index of the maximum element
}
max2 = input[i];
break;
}
// Find second maximum element and its index
for (i = 0; i < elements; i++) {
// Search for the second maximum element with the specified condition
if (input[i] > max2 && input[i] != max1) {
max2 = input[i];
index2 = i; // Update the index of the second maximum element
}
}
printf("\n2nd Max element is: %d at index %d\n", max2, index2);
return 0;
}