Skip to content Skip to sidebar Skip to footer

Javascript - Biggest Number From Array Using Loop

Can somebody please explain how this code gets which number from array is the biggest? var num = []; for( var i = 0; i < 10; i++ ) { num[i] = parseInt( prompt('Unesite broj

Solution 1:

To start, we've seen no numbers, and the code assumest the biggest is 0 or larger:

var biggest = 0;

We'll look at each number in the list:

for(i=0; i < num.length; i++ ) {

Is the current number bigger than the biggest we've seen?

if( num[i] > biggest ) {

If so, it's the new biggest number

    biggest = num[i];   
  }
}

When the loop is done, biggest contains the largest number we saw along the way.

Solution 2:

First for loop just prompts you to add numbers to an array.

The second loop just checks each number in the num array, if that number is bigger than the number in the biggest variable then it sets the biggest variable to that number.

It's as simple as that.

Solution 3:

The if statement within the loop checks whether the number in the current element of the array is greater than the largest number found so far. If the current number is the greatest, the largest number found so far is updated to this new number.

Post a Comment for "Javascript - Biggest Number From Array Using Loop"