6.8: Adding a continue Statement

Physical Modeling in MATLAB · LibreTexts

0%

Contents

    Text

    Size
    100%
    Theme
    Typeface
    Line length
    Spacing

    From LibreTexts, under CC BY-NC 4.0, as the source states it; its equations are written in TeX, which the PDF shows typeset. This page at LibreTexts.

    6.8: Adding a continue Statement

    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
                        continue
                    end
                    if is_pythagorean(a, b, c)
                        disp([a,b,c])
                    end
                end
            end
        end
    end

    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.8: Adding a continue Statement was last modified on Thu, 17 Nov 2022 18:19:01 GMT and is shared under a CC BY-NC 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.