Create the code to fill the array - Javascript/Logic

Asked

Viewed 63 times

0

I have a problem with an arrays exercise. The question is this::

Create the code to fill the array with the following values: 3 4 7 12 19 28 39 52 67 84

I’ve done the other exercises on that list, my problem with this is in logic. I can’t think of how to increment the counter so that it adds the next odd number. I even tried to elaborate as follows:

if((i+1)%2==0)
{
     numero = numero+i;
     contador= i;
}
else {
     numero= numero+2;
     contador =  i;
}

But it didn’t turn. Any help???

  • I think we need to explain what you want better and put the complete code. For example, what would be the initial value of i? Where is the array? Vc wants to insert only odd ones into the array?

  • Sam, there’s no code. I have to create a code that creates the list array= [3, 4, 7, 12, 19, 28, 39, 52, 67, 84] using loops. In this case I understood that the counter is incremented by 1 at the beginning and is being incremented with the next odd number (1, then 3, then 5, ...), but I can’t get it to run...

  • Right, but what is the maximum value to be added?

  • The last increment is in the value of 17, between elements 67 and 84!

1 answer

0


Resolution:

let n = 3;
let i = 1;
let a = [];

while(n <= 84){
    a.push(n);
    n += i;
    i += 2;
}

console.log(a);

  • Awesome!!! Thank you!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.