Find second largest number in array JavaScript
In this program, you will learn to find the largest number in an array by using for loop.
Program for second largest number in array for loop
<script>
var array = [5 , 60, 1, 56, 24, 6, 9, 38];
var largest=array[0];
var Second_largest=array[0];
var size=array.length;
for(i=1;i<size;i++)
{
if(array[i]>largest){
Second_largest=largest;
largest=array[i];
}
else if(array[i]>Second_largest && array[i]!=largest){
Second_largest=array[i];
}
}
document.write(Second_largest+" is second Largest number in an array");
</script>
output
56 is second Largest number in an array
Logic to find second largest number in an array
- Declares an array with 6 elements at the beginning.
- Declare
largestandSecond_largestvariable with an initial value of an array. - Find the size of the array and store it in variable
sizeby using the length method i.earray.length. - Inside the loop compare one by one array elements with the
largestvalue you have declared at the beginning. - If the array element is greater than the
largestvalue then copy thelargestvalue toSecond_largestand thecurrent arrayvalue tolargest.