-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

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

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;
    }
}

Comments

0
for (i=0;i<5;i++) {
    for (j=i+1;j<5;j++) {
        console.log(i + " and " + j);
    }
}

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);
  }
}

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.