0

I am trying to achieve 3,4,5 in output. But, am getting only 3,5 .its jumping/skipping one number. Donno why. Given my code below. Help me to fix the error and please let me know why its happening and what i am doing as error ?

Expected output,

3
4
5

output am getting,

3
5

my code,

var input1, input2;
input1 = Number(2);
input2 = Number(5);
for(let i=input1;i<input2;i++) {
    i=i+1;
    console.log(i);
  }

3 Answers 3

2

The for loop already increments i for you. The loop you wrote executes in the following path, going from 1 -> 2 -> 3 -> 4 -> 2 -> 3 and repeats unless the check at 3 is false:

for(
let i=input1; // 1. Declare initial value [i]
i<input2;     // 3. Check if [i] < [input2]
i++           // 4. increment [i] by 1
) 
{             
  i=i+1;      // 2. Run the contents of the loop body
  console.log(i);
}

That means

// First iteration
i = input1        // 1. i = Number(2);
  i = i + 1;      // 2. i = 2 + 1;
  console.log(i)  // 2. console.log(3);
i < input2 ?      // 3. Check if i is smaller than input2. End loop if not
i++;              // 4. Increment i so i = 4

// Second iteration
  i = i + 1;      // 2. i = 4 + 1;
  console.log(i)  // 2. console.log(5);
i < input2 ?      // 3. Check if i is smaller than input2. End loop if not

// End loop since i < input2 is not true
Sign up to request clarification or add additional context in comments.

Comments

2

You are incrementing i inside the body of the for loop even though it already does it for you.

input1 should also be 3.

Use:

var input1, input2;
input1 = Number(3);
input2 = Number(5);
for (let i = input1; i <= input2; i++) {
  console.log(i);
}

1 Comment

Thanks for the fastest reply it works after removing i=i+1;
1

You are incrementing variable 'i' two times

  1. On for loop
     for(let i=input1;i<input2;i++) {}
    
  2. Inside for loop
      i=i+1; 

So your variable 'i' will increment with 2

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.