View Full Version : arithmetic in javascript

06-11-2007, 03:19 PM
i have written the following code however it doesn't function as intended. the final for loop needs to report the greatest number in the array aswell as the day it occured. i am a complete novice but i am guessing the numbers need to be converted to carry out the necessary arithmetic. any help would be greatly appreciated. i'm sure it very simple but i am struggling to work it out.

<TITLE> books borrowed

/* Program to read in a known number of data items and store them in an array */

var booksBorrowed = new Array (5);
var dayNamesArray = ['monday', 'tuesday', 'wednesday', 'thursday', 'friday'];
var maxNumberBooks;

document.write('Array program to read in a known number of data items');
for (var day = 0; day < booksBorrowed.length; day = day + 1)
booksBorrowed[day] = window.prompt('Enter number of books borrowed on ' + dayNamesArray[day],'')
document.write('<BR>' + '<BR>');
document.write('Confirmation of data input' + '<BR>' + '<BR>');

for (var day = 0; day < booksBorrowed.length; day = day + 1)
document.write('the amount of books borrowed on ' + dayNamesArray[day] + ' is ' + booksBorrowed[day] + '<BR>')

maxNumberBooks = 0
for (var day = 0; day < booksBorrowed.length; day = day + 1)
if (booksBorrowed[day] > booksBorrowed[maxNumberBooks])
maxNumberBooks = day

document.write('the greatest number of books borrowed was ' + booksBorrowed[maxNumberBooks] + ' on ' + dayNamesArray[maxNumberBooks])


Philip M
06-11-2007, 04:16 PM
As far as I can see this homework assignment is working fine.
But please alter "amount" of books to "number" or "quantity".
And don't place a semi-colon after }

06-11-2007, 04:31 PM
thanks for the reply, it works ok if i input numbers with the same amount of digits, for e.g 12, 16, 76, 97,54 but if i throw in a three digit number 12, 76, 137, 41, 54 it will return 76 as the greatest number?

06-11-2007, 05:00 PM
The value entered in the prompt is a string, so you have to convert it to number.

booksBorrowed[day] = Number(window.prompt('Enter number of books borrowed on ' + dayNamesArray[day],''));
But take note that if the user clicks on Cancel, the value would be NaN (Not a Number). You may want to do validation on it.

Array has built-in sort (http://devguru.com/technologies/javascript/10559.asp) function, you don't have to manually sort it.

function sortNumbers(a, b) { return b - a} //descending order

alert(booksBorrowed[0]); //max number

06-11-2007, 06:31 PM
thats great! thanks for your help