To find the second largest number in an array using C language, you can follow a simple approach that involves iterating through the array to find the maximum element and then finding the maximum again while ignoring the first maximum.
Example:
#include <stdio.h>
#define MAX_SIZE 100
// Function to find the second largest number in an array
int findSecondLargest(int array[], int size) {
int firstMax = array[0]; // Initialize firstMax to the first element
int secondMax = array[0]; // Initialize secondMax to the first element
// Find the first maximum element
for (int i = 1; i < size; i++) {
if (array[i] > firstMax) {
secondMax = firstMax; // Update secondMax to previous firstMax
firstMax = array[i]; // Update firstMax to the new maximum element
} else if (array[i] > secondMax && array[i] != firstMax) {
secondMax = array[i]; // Update secondMax if the current element is greater than the current secondMax
}
}
return secondMax;
}
int main() {
int arr[MAX_SIZE] = {2, 4, 6, 8, 10, 12, 14}; // Example array
int size = 7; // Current size of the array
// Call the findSecondLargest function to find the second largest number
int secondLargest = findSecondLargest(arr, size);
// Print the second largest number
printf(“Second largest number: %d\n”, secondLargest);
return 0;
}
Explanation:
- We have a function
findSecondLargestthat takes the array and its size as parameters. - Inside
findSecondLargest, we initialize two variablesfirstMaxandsecondMaxto the first element of the array. - We then iterate through the array to find the maximum element (
firstMax). While doing so, we also updatesecondMaxif we encounter a number greater than the currentsecondMaxbut not equal tofirstMax. - Finally, we return
secondMax, which represents the second largest number in the array. - In the
mainfunction, we define an example arrayarrand its sizesize. - We call the
findSecondLargestfunction to find the second largest number in the arrayarr. - The second largest number is then printed.