Opening the book…
The break statement is used to exit a loop immediately. When MATLAB reaches break, it leaves the loop even if the loop condition would otherwise continue.
Example: Password Check
Suppose we want to keep asking a user for a password until the correct password is entered. We can create an infinite loop using while true, and then use break to exit the loop when the password is correct.
correctPass = 'abc';
while true
password = input('Please enter your password: ', 's');
if strcmp(password, correctPass)
break;
end
end
disp('Welcome!');
Notice that this example uses strcmp to compare character vectors. In MATLAB, text comparisons should generally be done with functions such as strcmp or strcmpi, not with ==, especially when comparing words or phrases.
Important Correction
When comparing text such as passwords, use strcmp(password, correctPass). Do not rely on password == correctPass for general text comparisons.
When Should You Use break?
The break statement is useful when you want the loop to stop as soon as a certain event happens. For example, you might use break when:
- a search value is found,
- a correct password is entered,
- a user chooses to quit, or
- continuing the loop is no longer necessary.
This page titled 6.7: The break Statement was last modified on Tue, 30 Jun 2026 02:11:42 GMT and is shared under a CC BY-NC-SA license and was authored, remixed, and/or curated by Zara Noroozi.
The book could not be loaded just now.