C Exercises: Find the second largest element in an array
C Array: Exercise-16 with Solution
Write a program in C to find the second largest element in an array.
The task is to write a C program that finds the second largest element in an array. The program should prompt the user for the array size and elements, then calculate and display the second largest element in the array.
Visual Presentation:
Sample Solution:
C Code:
#include <stdio.h>
void main() {
int arr1[50], n, i, j = 0, lrg, lrg2nd;
// Prompt user for input
printf("\n\nFind the second largest element in an array :\n");
printf("-------------------------------------------------\n");
printf("Input the size of the array : ");
scanf("%d", &n);
// Input values for the array
printf("Input %d elements in the array :\n", n);
for (i = 0; i < n; i++) {
printf("element - %d : ", i);
scanf("%d", &arr1[i]);
}
// Find the location of the largest element in the array
lrg = 0;
for (i = 0; i < n; i++) {
if (lrg < arr1[i]) {
lrg = arr1[i];
j = i;
}
}
// Ignore the largest element and find the second largest element in the array
lrg2nd = 0;
for (i = 0; i < n; i++) {
if (i == j) {
i++; // Ignore the largest element
i--;
} else {
if (lrg2nd < arr1[i]) {
lrg2nd = arr1[i];
}
}
}
// Display the second largest element
printf("The Second largest element in the array is : %d \n\n", lrg2nd);
}
Sample Output:
Find the second largest element in an array : ------------------------------------------------- Input the size of array : 5 Input 5 elements in the array : element - 0 : 2 element - 1 : 9 element - 2 : 1 element - 3 : 4 element - 4 : 6 The Second largest element in the array is : 6
Flowchart:
C Programming Code Editor:
Previous: Write a program in C to delete an element at desired position from an array.
Next: Write a program in C to find the second smallest element in an array.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://www.w3resource.com/c-programming-exercises/array/c-array-exercise-16.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics