-3

So I have a certain amount of people standing in line. I want to give each one of them a candy but each next person in line should get more candies. For example: 1st gets 1, 2nd gets 2, 3rd gets 3 and so on.

And what I need is to get total amount of candies given the amount of people.

Here's what I have so far (and I know it's totaly wrong but I'm lost):

function getTotalAmount(people) {

let candy;

for (candy = 0; true; candy++) {

return candy;

}

}
  • There is a closed formula for [this problem](https://en.wikipedia.org/wiki/1_%2B_2_%2B_3_%2B_4_%2B_%E2%8B%AF). NB: An unconditional `return` in a loop means that the loop will not loop: you exit immediately. – trincot Oct 26 '20 at 18:43

3 Answers3

1

Just add the index ( the position of the person in the line ) to the existing number of candies. This is in the case that each person receives the same number of candies as their position in the line.

function getTotalAmount(people) {

  let candy = 0

  for (let i = 0; i < people; i++) {

    candy += i

  }

  return candy

}
console.log(getTotalAmount(10))
Mihai T
  • 17,254
  • 2
  • 23
  • 32
0

Do you mean something like this :

let people = 7;

let sumCandy = 0;

for(let i = 0; i<people; i++, sumCandy+=i);

console.log(sumCandy);

which is called Fibonacci

codeanjero
  • 674
  • 1
  • 6
  • 14
0
function getTotalAmount(people) {
    let sum = 0;

    for(let i = 1; i <= people; i++) {
        sum = sum + i;
    }

    return sum;
}
Simon
  • 369
  • 1
  • 9