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);
}
CodePudding user response:
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);
}
CodePudding user response:
You are incrementing variable 'i' two times
- On for loop
for(let i=input1;i<input2;i ) {} - Inside for loop
i=i 1;
So your variable 'i' will increment with 2
CodePudding user response:
The for loop already increments i for you. The loop you wrote executes in the following path, going from 1 -> 2 -> 3 -> 4 -> 2 and repeats unless the check at 2 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
