0

I'm trying to make a loop where one value goes up while the second goes down.. I cant figure it out. As far as I can see checkNumber counts down correctly, and x and i are incorrect

I know i'm making a silly mistake somewhere but I'm brand new to coding

var checkNumber = 5;
for (var x = 0; x < 5; x++) {
  for (var i = 0; i < checkNumber; i++) {
    console.log(checkNumber);
    checkNumber = checkNumber - 1;
    console.log("x",x,"i",i);
  }
}

2
  • What do you mean by incorrect? What is the output you're expecting? Commented May 1, 2018 at 16:15
  • Which language is it? Why have you tagged two languages? Commented May 1, 2018 at 16:16

3 Answers 3

4

Just use a single loop and take the difference of the max value and the actual value (minus one, because of the zero based nature) for the second value.

var value = 5,
    i;

for (i = 0; i < value; i++) {
    console.log(i, value - i - 1);
}

Sign up to request clarification or add additional context in comments.

1 Comment

this makes sense, i was probably trying to over complicate it. thanks.
1

I'm assuming you're trying to do this:

var checkNumber = 5;
for (var x = 0; x < checkNumber; x++) {
  for (var i = checkNumber - 1; i >= 0; i--) {
    console.log(checkNumber);
    console.log("x", x, "i", i);
  }
}

This will start i at 4 (minus one to avoid index issues if that's what you're looking for, otherwise remove the -1) and go down to 0.

The first loop will count up until 4.

The trick is to use i-- and set i to something higher, then stop the loop with the second condition in the for.

Does that make sense?

1 Comment

thanks for explaining a bit more. i've found this website to not be very easy on beginners and so it's nice to have people like yourself who take the time to help :)
1

This will make i start at 0 and j start at 4. While i goes up to 4, j will go down to 0.

var checkNumber = 5;

for(var i = 0, j = checkNumber - 1; i < checkNumber; i++, j--){
	console.log(i + " " + 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.