In this program, you will learn to find the largest number in an array by using 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>
56 is second Largest number in an array
largest
and Second_largest
variable with an initial value of an array.size
by using the length method i.e array.length.
largest
value you have declared at the beginning.largest
value then copy the largest
value to Second_largest
and the current array
value to largest
.