Skip to main content
Library homepage
 
Engineering LibreTexts

7.4.1: Compound if, elseif Logic Examples

  • Page ID
    89058
  • \( \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}}\)

    When we want to test if a variable is between 2 values, we can use compound if or elseif logic, as shown in the example below. 

     

    Example \(\PageIndex{1}\) Compound if-elseif with 'and' logic

    if (x<0) % 
        z = 100;
        beep

    % The next elseif statement determines if x is between 0 and 10 with compound logic.

    % Both (x>=0) and (x<10) have to be true.

    elseif ((x>=0) & (x<10))
        z = 200; 
        beep

       pause(0.6) % wait 0.6 seconds between beeps)

       beep

    else % For any other value of x, z is set to 0 and no beeps are made.

        z = 0;

    end

    z    % Show the value of z

    Solution

    Sample case 1: x = -5

    Output: z = 100 with 1 beep

    Sample case 2: x = 5

    Output: z = 200 with 2 beeps

    Sample case 2: x = 15

    Output: z = 200 with no beeps.

    .

    Example \(\PageIndex{2}\) BodyTemperature Compound if-else with 'or' logic

    % Body Temperature version 1
    % Normal body temperatures are between 36.1°C and 37.2°C
    % https://medlineplus.gov/ency/article/001982.htm
    % For this script, the user will input their body temperature:
    body_temp = input('Enter your body temperature in degrees C: ')
    if ((body_temp < 36.1) | (body_temp > 37.2))
       disp('Your body temperature is outside the normal range.')
       if (body_temp < 36.1) 
          disp('It is lower than normal.')
       else 
          disp('It is higher than normal.')
          disp('You may have an infection or illness.')
       end
    else
          disp('Your body temperature is normal.')
    end

    Solution

    Add example text here.


    This page titled 7.4.1: Compound if, elseif Logic Examples is shared under a CC BY-NC-SA 4.0 license and was authored, remixed, and/or curated by Carey Smith.