0

I have come across this problem and embarassed to say I have never devised a good solution that has left me feeling satisfied -

I want to count to a number and then once the number is reached start counting up from 0 again.

so in JavaScript, we might have

var incr = 0;

if (incr === 50) {
    incr = 0;
}
incr++;

is there a more elegant way to do that, or is this pretty much the only way to do it? I keep thinking there is a way to do it with Math.max or Math.min, but never have figured it out.

3 Answers 3

2

You can use mod by 50

incr %= 50
Sign up to request clarification or add additional context in comments.

Comments

1

Use modulus % for this.

incr++ % 50;

1 Comment

I don't know about JS but in Java this will not work: you have to store result of it like: incr = (incr++) % 50, but in this case incr will always be 0, since incr++ applies after expression calculation
-1

Dont know if this counts. But a simple for and while loop?

var targetNumber = 50;
while(true) // Some condition
{
    for (var i = 0; i < targetNumber; i++)
    {
        // Do stuff
    }
}

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.