0

I was making a program in which user can keep entering numbers till user enters a multiple of 10. So I wanted to created a for loop for that and didn't knew what should be the infinite loop condition for it.

Scanner sc = new Scanner(System.in);

int n;

for(int i = 1;true;i++) {
  n = sc.nextInt();
  if (n % 10 == 0) {
    break;
  }
}
System.out.println("Wake up to reality !");
1
  • 4
    You don't need a for loop. Just use while(true) {...} Commented Apr 15 at 8:14

1 Answer 1

8

To create an infinite loop using a for loop, you can simply omit the condition altogether. In fact, you can omit any (or all) the elements in the for loop's parentheses:

for(;;) {
    n = sc.nextInt();
    if (n % 10 == 0) {
        break;
    }
}

Having said that, the idiomatic way of creating an infinite loop is with a while loop. Note that for a while loop you can't just omit the condition, but must explxicity state a boolean expression that evaluates to true. The simplest way to do this, is, of course, to use the boolean literal true:

while (true) {
    n = sc.nextInt();
    if (n % 10 == 0) {
        break;
    }
}

However, for this usecase, IMHO it would be more readable to use a do-while loop. This way you're garunteed that the loop runs at least once, and the exit condition is part of the loop and easy (easier?) to notice:

do {
    n = sc.nextInt();
} while (n % 10 != 0);
Sign up to request clarification or add additional context in comments.

3 Comments

Great, but just a minor comment: I think the OP's question is "what should be the infinite loop condition" and I don't see this explicitly addressed here, hence the comment. It may be obvious to someone that the OP's condition is correct, but this doesn't seem the case for OP themselves. Can you please add such a statement? I believe such a clarification would help. Thank you in advance.
@gthanop fair point, thanks! I edited my answer to clarify that.
Oh, I actually interpreted the infinite loop condition as the n % 10 == 0 check, ie the condition which terminates the infinite loop (so I expected a statement like "condition n % 10 == 0 is correct" or something). But I see now your point, which is that OP means the condition of the for loop, ie the one which gets the loop going. Excuse me, I got confused initially.

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.