Learn
Loops
The break Keyword
Imagine you have a loop that is iterating over an array and you want to stop the loop as soon as you find a specific element. Without the break
keyword, the loop would continue until it reaches the end of the array, even if the desired element has already been found. By using the break
keyword, you can instantly exit the loop once the condition is met, saving valuable processing time and improving overall efficiency.
Syntax and Usage
In the above example, we use the break
keyword inside the loop's body as soon as we find the targetElement
in the array
. This immediately terminates the loop, skipping any remaining iterations.
Instructions
Find the number 5 in the array and add a conditional statement to break the loop when the number is found.
- Add an
if
statement inside thefor
loop that checks if the current element is equal to 5. - Use the
break
keyword inside theif
statement to exit the loop.
Sign up to start coding
Already have an account?
Sign In