In MATLAB, we use the loop control statements to alter the execution of loops. There are two loop control statements. These are described below:
break
statementcontinue
statementbreak
statementIn MATLAB, the break
statement terminates the execution of a loop and shifts the execution to the code after the loop.
count = 0;while count < 10if count > 7break;// terminate the loopfprintf('The value of count is \n', count);end// The output is:// The value of count is 0// The value of count is 1// The value of count is 2// The value of count is 3// The value of count is 4// The value of count is 6// The value of count is 7
In the example above, we use the break
statement to terminate the while
loop as the count
exceeds 7. This is why the output is only generated till count=7
.
continue
statementWe use the continue
statement to skip the iteration of a loop. Also, it helps execute the loop from the next iteration onwards.
count = 0;while count < 10if count == 5continue;// skip the iterationfprintf('The value of count is \n', count);end// The output is:// The value of count is 0// The value of count is 1// The value of count is 2// The value of count is 3// The value of count is 4// The value of count is 6// The value of count is 7// The value of count is 8// The value of count is 9
We use the continue
statement so that the while
loop skips an iteration when the count
equals 5. Therefore, the output does not display the count
value of 5 and continues from 6 onwards.