Reputation:
I have the following loop:
for (let i=0; i<7; i+=2) {
for (let j=i; j<i+2; j++) {
console.log(j);
}
console.log('\n');
}
If I execute it I get:
0
1
2
3
4
5
6
7
But it only works on even conditions (0-7 = 8), if I instead put i<8, I get the same:
0
1
2
3
4
5
6
7
Which is bad, it must has returned 8 at the end, but instead doesn't print it. I expect my result when the condition is not even like this:
0
1
2
3
4
5
6
7
8
How can I achieve it? Thanks for your help.
Upvotes: 1
Views: 41
Reputation: 9796
Although Nina's answer is better, for completeness, I post a corrected version of the code that you started with:
let n = 8;
for (let i=0; i<=n; i+=2) {
for (let j=i; j<i+2 && j <= n; j++) {
console.log(j);
}
console.log('\n');
}
Upvotes: 0
Reputation: 386680
You could use a single loop and add for each odd value a line feed after printing the value.
for (let i = 0; i <= 8; i++) {
console.log(i);
if (i % 2) {
console.log('\n');
}
}
Upvotes: 5