I'm trying to learn Javascript and I'm looking at the for loop.
I'm trying to loop through 4 numbers which I've done successfully.
for (i=0;i<5;i++) {
console.log(i + " and " + (i+1));
}
However I'm trying to achieve something like this:
0 1
0 2
0 3
0 4
1 2
1 3
...etc
Is that possible with a for loop?
Thanks
Terry
-
Yeah, just nest 2 loops.yent– yent2012年07月24日 09:58:51 +00:00Commented Jul 24, 2012 at 9:58
4 Answers 4
Firstly your loop will be iterating through 5 numbers. 0, 1, 2, 3, 4 (count them)
You can achieve this by using two nested for loops
for (var i = 0; i < 5; i++) {
for(var j = i+1; j < 5; j++){
console.log(i + " " + j);
}
}
this will give you:
0 1
0 2
0 3
0 4
1 2
...
3 4
NOTE: that this seems to match you pattern of not including "1 1" for example
Comments
I think the question is ask for just one for loop.
here is the correct answer you want to want:
for (i=0,j=0;i<5;i++) {
console.log(j + " and " + (i+1));
if(j<5&&i==4){
j++;i=0;
}
}
Comments
for (i=0;i<5;i++) {
for (j=i+1;j<5;j++) {
console.log(i + " and " + j);
}
}
Comments
Nested loops will do the trick:
for (var i = 0; i < 5; i++) {
for (var j = i + 1; j < 5; j++) {
console.log(i + ' and ' + j);
}
}