How to run the loop for 2 in 2?

Asked

Viewed 906 times

0

My solution:

function passandoPelosPares() {
for (var i=0; i <=6; i++)
  console.log ('aqui eu tenho o valor de' + i)
}

Reply 'insufficient':

Print out passandoPelosPares() must print:

aqui eu tenho o valor de 0
aqui eu tenho o valor de 2
aqui eu tenho o valor de 4
aqui eu tenho o valor de 6

What I’m doing wrong?

  • Did any of the answers solve your question? Do you think you can accept one of them? Check out the [tour] how to do this, if you haven’t already. You would help the community by identifying what was the best solution for you. You can accept only one of them. But you can vote on any question or answer you find useful on the entire site

3 answers

4

Probably missing a space in the printing, the automatic broker of the site wants something exact, can not miss even the space. But I took advantage and simplified and gave more performance to the code apart from the if, it doesn’t make sense to have that code you can do without it.

function passandoPelosPares() {
    for (var i = 0; i <= 6; i+= 2) console.log('aqui eu tenho o valor de ' + i);
}
passandoPelosPares();

I put in the Github for future reference.

I put the function call just to run here, there on this site it should call on its own and do not need this line.

  • Thank you, I remade the solution and it worked!

2

In your code in the loop for you’re always adding more 1 in the variable i every iteration of the loop for which will not give you the result in 2 and 2 and yes in 1 in 1, then change from i ++ for i += 2, add a space at the end of the String not to be together with the text and the number and just call the function passandoPelosPares();.

Example 1

function passandoPelosPares() {
for (var i = 0; i <= 6; i += 2)
  console.log ('aqui eu tenho o valor de ' + i)
}

passandoPelosPares();

In case you want a sequence in 2, 4, 6 and not 0, 2, 4, 6 just start the variable i with 2 and not with 0.

Example 2

function passandoPelosPares() {
for (var i = 2; i <= 6; i += 2)
  console.log ('aqui eu tenho o valor de ' + i)
}

passandoPelosPares();

  • Thank you very much for your contribution.

1

I executed your code and the result was:

aqui eu tenho o valor de0
aqui eu tenho o valor de2
aqui eu tenho o valor de4
aqui eu tenho o valor de6

Which leads me to believe that the problem is the gap between "de" and "par".

In this case, simply replace the "+" with "," in your console.log.

You don’t need the if if the step of your for for every 2, changing i++ for i+=2.

Also, it may be lacking to perform the function, and you can do this involving the function with () and putting the parentheses at the end, this way:

(function passandoPelosPares() { 
    for (var i=0; i <=6; i+=2) 
        console.log ('aqui eu tenho o valor de', i) 
})()

  • Thank you for your contributions.

  • But none of the solutions worked.

Browser other questions tagged

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