Skip to main content
Engineering LibreTexts

6.9: Adding a continue Statement

  • Page ID
  • \( \newcommand{\vecs}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \) \( \newcommand{\vecd}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash {#1}}} \)\(\newcommand{\id}{\mathrm{id}}\) \( \newcommand{\Span}{\mathrm{span}}\) \( \newcommand{\kernel}{\mathrm{null}\,}\) \( \newcommand{\range}{\mathrm{range}\,}\) \( \newcommand{\RealPart}{\mathrm{Re}}\) \( \newcommand{\ImaginaryPart}{\mathrm{Im}}\) \( \newcommand{\Argument}{\mathrm{Arg}}\) \( \newcommand{\norm}[1]{\| #1 \|}\) \( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\) \( \newcommand{\Span}{\mathrm{span}}\) \(\newcommand{\id}{\mathrm{id}}\) \( \newcommand{\Span}{\mathrm{span}}\) \( \newcommand{\kernel}{\mathrm{null}\,}\) \( \newcommand{\range}{\mathrm{range}\,}\) \( \newcommand{\RealPart}{\mathrm{Re}}\) \( \newcommand{\ImaginaryPart}{\mathrm{Im}}\) \( \newcommand{\Argument}{\mathrm{Arg}}\) \( \newcommand{\norm}[1]{\| #1 \|}\) \( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\) \( \newcommand{\Span}{\mathrm{span}}\)\(\newcommand{\AA}{\unicode[.8,0]{x212B}}\)

    As a final improvement, let’s modify the function so it only displays the “lowest” of each Pythagorean triple, and not the multiples.

    The simplest way to eliminate the multiples is to check whether a and b share a common factor. If they do, dividing both by the common factor yields a smaller, similar triangle that has already been checked.

    MATLAB provides a gcd function that computes the greatest common divisor of two numbers. If gcd(a,b) is greater than 1, a and b share a common factor and we can use the continue statement to skip to the next pair. Listing 6.1 contains the final version of this function:

    Listing 6.1: Our final Pythagorean triples function

    function res = find_triples(n)
        for a=1:n
            for b=a:n
                for c=b:a+b
                    if gcd(a,b) > 1
                    if is_pythagorean(a, b, c)

    The continue statement causes the program to end the current iteration immediately, jump to the top of the loop, and “continue” with the next iteration.

    In this case, since there are three loops, it might not be obvious which loop to jump to, but the rule is to jump to the innermost loop (which is what we want).

    Here are the results with n = 40:

    >> find_triples(40)
         3     4     5
         5    12    13
         7    24    25
         8    15    17
         9    40    41
        12    35    37
        20    21    29

    This page titled 6.9: Adding a continue Statement is shared under a CC BY-NC-SA 4.0 license and was authored, remixed, and/or curated by Allen B. Downey (Green Tea Press) via source content that was edited to the style and standards of the LibreTexts platform; a detailed edit history is available upon request.