Kahibaro
Discord Login Register

5.4 break, continue, and return

Controlling Loop Execution with `break`, `continue`, and `return`

In MATLAB, loops normally run until their loop condition is no longer satisfied. Sometimes you want to stop a loop early, skip part of a loop, or stop running a function entirely. The commands break, continue, and return give you fine control over this behavior. They are small keywords, but they change the flow of execution in important ways.

This chapter focuses only on how these three commands behave inside loops and functions, and how you can use them safely in beginner level programs.

The `break` Statement

The break statement stops the execution of the innermost loop that contains it. As soon as MATLAB executes break, it exits that loop immediately and continues with the next line of code after the loop.

Consider a for loop that searches for the first number greater than 10 in a vector. You can stop the loop once the value is found.

v = [2 5 9 12 15 3 18];
foundIndex = NaN;
for k = 1:length(v)
    if v(k) > 10
        foundIndex = k;
        break
    end
end
disp(foundIndex)

Here the loop was originally set to run from k = 1 to k = length(v). The break statement shortens the loop at runtime. After a value greater than 10 is found, MATLAB immediately leaves the loop and continues with disp(foundIndex).

If you have nested loops, break only exits the innermost loop where it appears. It does not exit any outer loop.

for i = 1:3
    for j = 1:5
        if j == 3
            break
        end
        fprintf('i = %d, j = %d\n', i, j);
    end
end

In this example the break stops only the j loop. The i loop continues with the next value of i. So, for each i, j will run only for 1 and 2.

You can also use break in a while loop. This is common when the loop condition cannot easily be written in a single logical expression.

x = 0;
while true
    x = x + 1;
    if x^2 > 50
        break
    end
end
disp(x)

Here while true creates an infinite loop in theory. In practice, the break condition inside the loop controls when the loop stops. This pattern is useful when you do not know in advance how many iterations are needed.

The `continue` Statement

The continue statement does not end the entire loop. Instead, it skips the rest of the current iteration and jumps directly to the next iteration of the loop.

This is helpful when you want to ignore certain values or cases without stopping the loop completely.

Suppose you want to sum only the positive elements of a vector. You can use continue to skip all nonpositive numbers.

v = [3 -1 4 0 5 -2];
s = 0;
for k = 1:length(v)
    if v(k) <= 0
        continue
    end
    s = s + v(k);
end
disp(s)

When v(k) is less than or equal to zero, MATLAB executes continue. It then ignores any remaining statements in the loop body for that iteration, and proceeds with the next value of k. The assignment s = s + v(k) is only executed when v(k) is positive.

You can also combine continue with multiple conditions. Sometimes this simplifies your loop by keeping special cases at the top and the main logic at the bottom.

for n = 1:10
    if mod(n,2) == 1
        continue
    end
    fprintf('Even number: %d\n', n);
end

In this loop, when n is odd the continue skips the printing statement, so only even numbers are displayed.

As with break, when loops are nested, continue affects only the innermost loop that contains it.

for i = 1:3
    for j = 1:5
        if j == 2
            continue
        end
        fprintf('i = %d, j = %d\n', i, j);
    end
end

In this example, the continue skips the body of the inner loop only when j == 2. The outer loop over i is unaffected.

You can use continue in while loops in the same way.

x = 0;
while x < 5
    x = x + 1;
    if x == 3
        continue
    end
    fprintf('x = %d\n', x);
end

Because of continue, the value 3 is not printed, while the loop continues for x = 4 and x = 5.

The `return` Statement

The return statement exits the current function and returns control to the caller. Execution continues with the line immediately after the function call.

When return appears inside a function file, MATLAB stops executing that function as soon as it reaches return. Any remaining lines in that function are not executed. If the function has output variables, their current values at the moment of return are passed back.

Consider a simple function that divides two numbers but handles division by zero specially.

function q = safeDivide(a, b)
    if b == 0
        q = NaN;
        return
    end
    q = a / b;
end

If the user calls safeDivide(5, 0), the body of the function sets q = NaN, executes return, and immediately exits. The line q = a / b; never runs, so division by zero is avoided. If b is not zero, the if condition is false, the return is skipped, and the function continues normally.

You can also use return inside loops that are inside functions. In that case, return exits the entire function, not just the loop.

function idx = findFirstNegative(v)
    idx = NaN;
    for k = 1:length(v)
        if v(k) < 0
            idx = k;
            return
        end
    end
end

Here the function stops as soon as it finds a negative value. The return leaves both the for loop and the function at once.

If a script file (not a function) contains return, MATLAB stops executing that script and returns to the Command Window or to the calling script or function. This is less common for beginners, but it can be used to exit a long script early.

Choosing Between `break`, `continue`, and `return`

break, continue, and return all change the normal flow of execution, but they act at different levels.

Use break when you want to stop a loop early, but still continue executing the code that follows the loop. This is typical for search tasks, where you only need the first match.

Use continue when you want the loop to keep running, but you want to skip the remaining lines in the body for specific iterations. This keeps the main logic of the loop simple and avoids deep nesting of if statements.

Use return only in functions or scripts when you want to exit completely from the current function or script. With functions, this often appears as an early exit, for example when input arguments fail a simple check or when a special case is encountered.

It is important to avoid overusing these commands especially once your code becomes more complex. Having many exit points inside loops and functions can make code harder to follow. For small, clear cases, however, they can make code shorter and easier to read.

Important points to remember:
break exits only the innermost loop and continues with the first line after that loop.
continue skips the rest of the current iteration of the innermost loop and starts the next iteration.
return exits the current function or script immediately and continues after the call site.
In nested loops, both break and continue affect only the loop they are directly inside.
Use these commands for clear and simple control flow, but avoid making your code hard to read with too many early exits.

Views: 41

Comments

Please login to add a comment.

Don't have an account? Register now!