0

I'm sure that this is simple, but the solution is eluding me. I want to write a function that will result in: 1000 + 1001 + 1002 + 1003 + 1004 (so I'll output 5010)

I have a form where the user inputs a number x (1000 in this case) and a number of times it will iterate y (5 in this case)

I know that I need to store the value each time through in var total, but I'm not quite getting it.

I have this so far:

function baleTotal(){
  var x = document.addBale.strt.value;
  var y = document.addBale.baleNum.value;
  var calc = Number(x);
  total = 0;

  for (var y; y > 0; y--) {
   calc++;
  }              

  document.addBale.result.value = total;
}
3
  • for (var y; y > 0; y--) <--- what's this? Commented Apr 3, 2014 at 23:08
  • 1
    You increment calc in your loop but do nothing with it. Commented Apr 3, 2014 at 23:08
  • Right, I had been setting the output value to calc, which gave me 1005 , which is just the iteration. I need to do something like total = total + calc, but I've tried that. Commented Apr 3, 2014 at 23:16

4 Answers 4

2

You're not actually adding to your total. This does the calculation given the base and the number of iterations and returns the result, rather than operating directly on the DOM.

function baleTotal(base, iterations) {
    var total = 0;
    for (i=0; i<iterations; i++) {
        total += (base + i);
    }
    return total;
}

console.log(baleTotal(1000, 5));
Sign up to request clarification or add additional context in comments.

Comments

0

You are not doing anything with total and also you are redeclaring y. Try this:

function baleTotal(){
  var x = document.addBale.strt.value;
  var y = document.addBale.baleNum.value;
  var calc = Number(x);
  total = 0;

  for (; y > 0; y--) {
   total += calc + y;
  }              

  document.addBale.result.value = total;
}

Not tested but should work.

Comments

0

Is this more or less what you mean?

function baleTotal(){
  var x = document.addBale.strt.value;
  var y = document.addBale.baleNum.value;
  total = 0;

  for (var i = 0; i < y; i++) {
   total += x + i;
  }             

  document.addBale.result.value = total;
}

Comments

0

I think this is what you're looking for.

function baleTotal(){
  total = 0;
  for (var i = 0; i < document.addBale.baleNum.value; ++i) {
    total += document.addBale.strt.value + i;
  }
  document.addBale.result.value = total;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.