-1

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

Sirko
74.4k19 gold badges157 silver badges194 bronze badges
asked Jul 24, 2012 at 9:57
1
  • Yeah, just nest 2 loops. Commented Jul 24, 2012 at 9:58

4 Answers 4

1

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

answered Jul 24, 2012 at 9:59
Sign up to request clarification or add additional context in comments.

Comments

0

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;
 }
}
answered Jul 24, 2012 at 10:05

Comments

0
for (i=0;i<5;i++) {
 for (j=i+1;j<5;j++) {
 console.log(i + " and " + j);
 }
}
answered Jul 24, 2012 at 10:00

Comments

0

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);
 }
}
answered Jul 24, 2012 at 10:02

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.