SECOND LARGEST ELEMENT IN AN ARRAY : C++ SOLUTION EXPLAINED

Spread the love

Well, array is the collection of elements of same data type. Like either all the elements can be integer, float or character or of any other data types.

To find the second largest element in an array, we have to compare each elements in the array. We have to use the looping structure till the expected result is gained.

Logic can be:

here, both largest and seclargest is initialized by min value.

so here, we compare the each element with largest value. here have two if conditions.

first condition is for collecting the largest and the second largest element. When we compare arr[i] with largest, automatically one is the largest and second one is the second largest from one iteration. This continues till all the elements in the array are compared. And if the first condition is true then the largest and the second largest value is updated each time.

If the first condition is false, meaning we have already got the element. But since we have to whether the element is required element or not. So for this we come to another condition where it is compared with second largest element and to be the second largest, it shouldn’t be equal to largest one.


Spread the love

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top