% getMode: Determine the mode of a non-decreasing, non-negative sequence

% Written by Paul Chew for CS100M, Feb 2006

modeCount = 0;
mode = -1;          % Best choice for mode so far
currentCount = 0;
current = -1;       % Most recently seen sequence item
number = input('First number of sequence: ');
while number >= 0
    if current == number
        currentCount = currentCount + 1;
        if currentCount > modeCount
            modeCount = currentCount;
            mode = current;
        end
    elseif current < number
        currentCount = 1;
        current = number;
    else
        disp('Sequence must be non-decreasing; bad input ignored');
    end
    number = input('Next number of sequence: ');
end
if modeCount == 0
    disp('The mode is undefined')
else
    fprintf('The mode is %d which occurred %d times\n', mode, modeCount);
end
