Tony Tambe
Tony Tambe

Reputation: 573

Javascript Calculation Using For Loop

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;
}

Upvotes: 0

Views: 106

Answers (4)

p.kamps
p.kamps

Reputation: 86

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;
}

Upvotes: 0

Stephen P
Stephen P

Reputation: 14830

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));

Upvotes: 2

graemeboy
graemeboy

Reputation: 610

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;
}

Upvotes: 0

Octavian
Octavian

Reputation: 4589

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.

Upvotes: 0

Related Questions