1

I have a game with a computer AI that saves info to an array and I need to loop through the array, which is fine but once it finds the value I'm looking for it keeps searching, normaly this would not be a problem but the arrays can get quite large and I'd prefer to be able to simply stop the loop once I have the values that I need.

1 Answer 1

6

Use the break statement:

for (int i = 0; i < 10000000; i++) {
    if (i == 2) {
        // Exit the loop on the 3rd iteration
        break;
    }
}

This also works in (for ... in ...) loops.

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

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.