Answer:
#include <stdio.h>
int getElement(int arr[], int size) {
int largest2, largest = 0;
for(int i=0; i<size; i++)
{
if(arr[i] > arr[largest])
{
largest = i;
}
}
if(largest != 0)
largest2 = 0;
else
largest2 = size - 1;
for(int i=0; i<size && i != largest ;i++)
{
if(arr[i] > arr[largest2])
largest2 = i;
}
return arr[largest2];
}
printArray(int arr[], int size) {
printf("The array is: ");
for(int i=0; i<size; i++)
{
printf("%d ", arr[i]);
}
printf("\\");
}
int main()
{
int arr[5] = {30, 20, 5, 10, 24};
printArray(arr, 5);
printf("Second largest number is: %d", getElement(arr, 5));
return 0;
}
Step-by-step explanation:
Since you did not provide any code, I wrote it from the scratch. I also added the main function for you to check the result.
printArray function basically prints the element of the array
getElement function:
- Declare the two variables to hold the value for largest and second largest
- Inside the first loop, check if there is any number that is greater than largest, if yes, assign it to largest
- Inside the second for loop, check if there is any number that is greater than largest2, if yes, assign it to largest2 (Be aware that the largest we found in the first loop is excluded)
- Return the second largest
* Notice that we were able to apply this solution since the numbers are unique.