Examples

  1. Correct the indentation of this code fragment and manually trace its execution to determine what is displayed if x > 5.

    % assume input_value was set earlier to contain 10 numbers
    for i = 1:10
        x = input_value(i);      % a vector of values from the user
        if x > 5
            y = x^3 + x - 120;
        else if x > 0            % NOTE there's a blank between else and if
            y = 2*x;
        elseif x >= -2
            y = x^2;
        else 
            y = x^4 / 4;
        end
            disp(['For x = ', num2str(x), ' y = ', num2str(y)]);
        end
    end
    Formatting this text using Text->Smart Indent makes it easier to see that the disp command will never execute if x > 5. Here is how Smart Indent formats the above code:
    % assume input_value was set earlier to contain 10 numbers
    for i = 1:10
        x = input_value(i);     % a vector of values from the user
        if x > 5
            y = x^3 + x - 120;
        else 
            if x > 0            % NOTE there's a blank between else and if
                y = 2*x;
            elseif x >= -2
                y = x^2;
            else 
                y = x^4 / 4;
            end
            disp(['For x = ', num2str(x), ' y = ', num2str(y)]);
        end
    end

    Note that the disp statement is inside the first else clause, so when the x > 5 condition is true, the disp statement will not be executed.

  2. In the nested loop example below, when the break is encountered, just the while loop is exited; the body of the for loop continues to execute (starting at the statement after the while loop).

    for trial = 1 : 10
    
        count = 0;    % initialize count of rolls
        while 1 == 1  % keep rolling forever (until we get a 4)
            die = randperm(6);
            top_of_die = die(1);
            count = count + 1;
            if top_of_die == 4  % if we rolled a 4
                break           % stop
            end
        end
        
        % the break causes control to jump here
        disp(['Trial ', num2str(trial), ': it took ', ...
              num2str(count), ' rolls to get a 4'])
    end
    

    Again, using break statements to exit loops can create code that is harder to debug.

  3. What is the output of this nested code fragment?

    Manually trace the code instead of entering it and running the code in Matlab.

    clear;
    a = 1;
    b = 12;
    c = 3;
    for month = a : c : b  % for every third month of the year 
        while month <= 6 % for first half of the year
            if rem(month,2) == 0
                disp('Yippee, it''s an even month');
            else
                disp('Too bad, it''s an odd month');
            end
        end
    end
    

    Did you discover the infinite loop? If not, try manually tracing the loops more carefully. Of, enter and save the code in a Matlab script, set a breakpoint at the start of the for loop, and step through the code using Matlab's debugging tools.

  4. Fix the above code fragment so that it outputs for only the first half of the year. No output should be produced for the second half of the year.

    clear;
    a = 1;
    b = 12;
    c = 3;
    for month = a : c : b  % for every third month of the year 
        if month <= 6 % for first half of the year
            if rem(month,2) == 0
                disp('Yippee, it''s an even month');
            else
                disp('Too bad, it''s an odd month');
            end
        end
    end
    

    The while loop here is incorrect and would interfere with the execution of the outer for loop if the condition variable month were to be updated within the body of the while loop. In this case, the while loop should really be an an if statement.

    If an inner loop is really necessary, use a new variable to control the inner loop and be sure to update the value of the condition variable in the body of the loop.