Hi, I have a programme in which I have written three functions, difference (that calculates the difference in numbers between arrays) sum (that totals the array up) and calculate difference which uses the difference function to determine what the next array should be).
All these functions are working but I'm having problems getting the while loop to work in the main programme and I can't see where I am going wrong!
If anyone could point me in the right direction then I would appreciate it. The programme is supposed to write out the initial array. It then calculates the new array and writes it out (which it does so far). I then need to loop it round so that while ever the sum is not 0 the programme runs and counts how many times it takes to repeat the process in order to reach 0. I thought that I would have to set the values of the numberArray back to the new figures from calculate difference and then clear the calculate difference array out. I've been working at this for days and I'm no closer to working out what I need to do. I'm not wanting people to give me the answer as it is for my coursework but I would like some guidance as to where I am going wrong.
function difference(firstNumber, secondNumber)
{
if (firstNumber > secondNumber)
{
return (firstNumber - secondNumber);
}
else
{
return (secondNumber - firstNumber);
}
}
function sum(numberArray)
{
numberTotal = 0
for (var total = 0; total < numberArray.length; total = total + 1)
{
numberTotal = numberTotal + numberArray[total]
}
{
return numberTotal
}
}
function calculateDifferences()
{
var createArray = new Array(numberArray.length);
for (var c = 0; c < numberArray.length - 1 ; c = c + 1)
{
createArray[c] = difference(numberArray[c],numberArray[c+1]);
}
{
createArray[numberArray.length - 1] = difference(numberArray[0],numberArray[numberArray.length - 1]);
}
{
return createArray;
}
}
var numberArray = [16,14,4,5];//initial numbers to start with
document.write(numberArray +'<BR>');//writes out initial numbers
sum(numberArray);// checks to see if sum total = 0
var count = 0;// delcares the counter to 0
while(sum(numberArray) > 0)// runs the programme while sum is not 0
{
count = count + 1;// counts how many times looped
calculateDifferences(numberArray);//calculates the new numbers from numberArray
document.write (calculateDifferences() + '<BR>');//writes out new numbers
calculateDifferences = numberArray;// sets the numberArray to new figures
calculateDifferences() = 0;//clears array for next calculate
sum (numberArray);//checks the condition again
}
document.write ( 'interations taken = ' + count + '<BR>');//if sum 0 then programme finishes by writing out how many times it took to get to 0