5.5: The if-else Statement

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.5: The if-else Statement

    An if-else statement is used when there are two possible actions. If the condition is true, MATLAB runs the first action. Otherwise, MATLAB runs the second action.

    if condition
    action1
    else
    action2
    end

    In the following example, the user is asked to enter the diameter of a circle. If the diameter is invalid, the program prints an error message. Otherwise, it calculates the perimeter.

    Example \(\PageIndex{1}\)

    Perimeter of a circle.

    % circlePerimeter.m
    % This script calculates the perimeter of a circle.
    % It also checks whether the diameter is valid.
    
    diam = input('Please enter the diameter: ');
    
    if diam <= 0
        fprintf('Sorry; %.2f is not a valid diameter.\n', diam)
    else
        perimeter = pi * diam;
        fprintf('For a circle with diameter %.2f, ', diam)
        fprintf('the perimeter is %.2f.\n', perimeter)
    end
    Solution
    If the user enters -1, for example, the message will be: Sorry; -1.00 is not a valid diameter.
    If the user enters 2, for example, the message will be: For a circle with diameter 2.00, the perimeter is 6.28.
    

    This version is more user-friendly because it gives feedback no matter what the user enters.


    This page titled 5.5: The if-else Statement was last modified on Tue, 30 Jun 2026 02:11:52 GMT and is shared under a CC BY-NC-SA license and was authored, remixed, and/or curated by Zara Noroozi.