skip to Main Content

How can I increase the value stored in count by one every time it is a multiple of 2

I have a function that returns the value of i, it is initialized to 0 and it is auto-incrementing, that is, when i is a multiple of 2, the counter has to increases by 1

I try to do is that when i is a multiple of 2, the variable count has to increase in 1

This is the code I’m doing, could you tell me where my error is?

let count = 0;
        
if( i % 2  == 0){               
  count++;
  console.log(count);       
}else{

}

2

Answers


  1. You should divide count by 2, not i

    let count = 0;
    
    if( count % 2 == 0){
        count++; console.log(count);    
    }else{
    
    }
    

    By the way, your code only runs once. So it seems that your code lacks some sort of a loop. There needs to be a for or while loop.

    Update:

    based on your comments, I think your code should look like this:

    let count = 0;
    let i = 0;
    // set a limit, for example 100
    while(i < 100){
      i = updateI(); // get the new value for i
      if( i % 2 == 0)
      {
         count++; console.log(count);    
      }else{
    
      }
    }
    
    Login or Signup to reply.
  2. Maybe the full script like this. it works fine

    let count = 0;
    let i = 0;
    while(i < 10){
      i++;
      if(i % 2 == 0){    
        count++
        console.log('even number',i, 'of',count);       
      }
    }
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search