- Explanation of the logic
Introduction of the second largest number
Finding the second largest value in an array is a classic C array program.
This program gives you an insight into the iteration, and array. Also, conditional operators.
We iteratively check each element to determine the largest and second largest element.
Algorithm of second largest number program
- Find the largest number
- Find the smallest number
- If both are the same, all are the same
Explanation of the logic
Consider the Smallest number as the second largest. Do a comparison of all the numbers one by one in an array.
The number which is greater than the Second largest number, should not be greater than the largest number.
Then we got the second largest number.
In the program, the first while loop has been dedicated to accepting the numbers from the keyboard and the second while loop is for finding the largest and smallest number so the if loop compares the smallest and the largest number.
If they are equal, the second largest number cannot be determined. In the else part, we have compared the numbers in the array with the second largest.
If it is greater than this and not the same as the largest number then that is the second largest number.
Finally, we have printed it and this is how the implementation works in this program.
Accept 10 numbers in an array and determine the second largest number.
Note: User may feed the same number 10 times. In this case, print all are the same.
printf(“Enter a number:”);
if(smallest == largest)
printf("All are same, second largest cannot be determined");
if(x[y]>secondLargest && x[y]!=largest)
printf("Second largest: %d\n",secondLargest)
Enter a number: 12
Enter a number: -1
Enter a number: 36
Enter a number: 54
Enter a number: 7
Enter a number: 82
Enter a number: 62
Enter a number: 95
Enter a number: 80
Enter a number: 5
Second Largest: 82
So, here is all about the second largest number in the array in C. We have tried our best to explain the logic and program so we hope you find this implementation alternative. Stay tuned for the upcoming blogs.