5.2: Why Programs Need Branches

Fundamentals of MATLAB Programming · LibreTexts

0%

Contents

    Text

    Size
    100%
    Theme
    Typeface
    Line length
    Spacing

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

    5.2: Why Programs Need Branches

    So far, many of the MATLAB programs you have written probably run in a straight line. MATLAB starts at the first statement, executes it, moves to the next statement, and continues until the script or function is finished. This works well for simple calculations, but real programs usually need to make choices.

    For example, imagine that you write a program that calculates the square root of a number. The square root of a positive number is straightforward. But what if the user enters a negative number by mistake? The program should not blindly continue as if nothing happened. It should check the input and decide what to do next.

    There are several possible algorithms. One program might reject the negative input and ask the user to try again. Another program might automatically convert the number to a positive value before calculating the square root. In both cases, the program must make a decision. This decision creates a branch in the code.

    Note

    A branch allows a program to choose whether to run certain statements based on a condition. In MATLAB, the two main branching tools are if statements and switch statements.


    This page titled 5.2: Why Programs Need Branches was last modified on Tue, 30 Jun 2026 02:11:17 GMT and is shared under a CC BY-NC-SA license and was authored, remixed, and/or curated by Zara Noroozi.