Function with for()

Asked

Viewed 647 times

-1

I have a problem in an exercise. In this exercise, I must implement a function called passandoPelosPares() that shows by the console aqui eu tenho o valor de x for each PAR value running i from 0 to and including 6.

Tip:

To know if a number is even, we use the operator % (module) that returns me the rest of the division of one number by another. For example: 11 % 5 returns the rest of division 11 by 5, which in this case returns 1.

My created function:

function passandoPelosPares(){
  
  for (var i = 0; i<=6; i++){
    
    if(i%2==0||i%4==2||i%6==4||i%8==6){
     console.log("aqui eu tenho o valor de " + i); 

  }
 }  
}

But even returning the correct values until the 6, is still being presented the following error:

'[object Object]' == 'aqui eu tenho o valor de 0\naqui eu tenho o valor de 2\naqui eu tenho o valor de 4\naqui eu tenho o valor de 6\n'

Could you help me?

  • The result seems to be as expected, although your if has more checks than necessary. Which error is being presented?

  • I agree with Daniel Mendes. We can prove that if x % 2*n == 2*m, then x % 2 == 0 is true. Soon, everything after the first conditional is redundant: they can only give true if the first condition (i % 2 == 0) is true, and will always be false when the first condition is also false.

  • Thank you very much for the personal clarification.

2 answers

0

Hello! Running your function, is not occurring this error you are stating. What you are interpreting as an error is actually just the reflection of the code in the code inspector of your browser or app you are using.

There is another question involving the same function here. For more clarification see: How to run the loop for 2 in 2?

function passandoPelosPares(){
   for (var i = 0; i<=6; i++){
      if(i%2==0||i%4==2||i%6==4||i%8==6){
         console.log("aqui eu tenho o valor de " + i); 
      } 
   }
}

passandoPelosPares();

Click on "Run" and see the normal result as expected by you.

  • Valmor flowers, thank you so much for your help

0

only loop and IF comparing if its divisor is equal to 0! the divisor is equal to 0 always an even number.

Passing Function PelosPares(){ for(var i = 0; i <= 6; i++) { if (i % 2 == 0) { console.log("here I have the value of "+i) } } }

Browser other questions tagged

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