Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding largest element in an array

I am trying to write a JavaScript program that will display the largest number out of 10 numbers inputted by the user. This is what I have so far but it isn't working.

var counter = 1;
var number = new Array();
number.length = 9;
var largest = 0;

while (counter <= 10) {
    number = window.prompt("Enter Numbers 1-10 Number:" + counter + ".");
    number[counter] = parseInt(number);
    counter++;
}

largest = Math.max.apply(Array);
document.writeln("<h1>Largest number is " + largest + "</h1>");
like image 426
Jessica Avatar asked Sep 05 '25 02:09

Jessica


2 Answers

You have several issues:

  1. Arrays are 0 indexed. You skipped the 0 index by starting the counter at 0, this will screw up the array calculation. If you go with Math.max.apply(array, number), it will work without the 0 indexing.

  2. You overwrote the number variable with every prompt, either use the window.prompt to feed into the parseInt or feed it into a temporary variable.

  3. You had incorrect syntax for the apply variable.

var counter = 0;
var number = new Array();
number.length = 9;
var newnumber;
var largest = 0;

while (counter <= 10) {
    newnumber = window.prompt("Enter Numbers 1-10 Number:" + counter + ".");
    number[counter] = parseInt(newnumber);

    counter++;
}

largest = Math.max.apply(Math, number);
document.writeln("<h1>Largest number is " + largest + "</h1>");
like image 175
Snowburnt Avatar answered Sep 06 '25 17:09

Snowburnt


You're simply missing the expected thisArg for Function.prototype.apply.

The Syntax, as described by MDN is

fun.apply(thisArg[, argsArray])

As shown in this simple example

Math.max.apply (null,[5,4,3,7,9,]) //9
                ^^^^

where null is used in the example for simplicity, as Math doesn't expect an specific context

What you are trying to do is passing the array number to Math.max, which would then be the thisArg (though you seem to have it mistaken with Array) which would result either way in Math.max being called with zero arguments, which yields according to §15.8.2.11

Given zero or more arguments, calls ToNumber on each of the arguments and returns the largest of the resulting values.

  • If no arguments are given, the result is −∞.
like image 32
Moritz Roessler Avatar answered Sep 06 '25 18:09

Moritz Roessler