% Guess a number between 0 and 1024

% Get a number to guess, with care
HaveNumber = 0;
while ~HaveNumber
    Number = input('Enter a number between 0 and 1024 -> ')
    if Number > 1024
        warning('Number must be < 1024, go again.');
    elseif Number < 0
        warning('Number must be > 0, go again.')
    else
        HaveNumber = 1;
    end
end

% Start guessing: Number will be between LowEnd and HighEnd
HighEnd = 1024;
LowEnd = 0;
Tries = 0
for n = 1:10 % We'll never need more than 10 guesses
    Tries = Tries+1;
    MyGuess = LowEnd + (HighEnd-LowEnd)/2;
    fprintf('Guess: %d', MyGuess);
    
    % distinguish 3 cases
    % 1. Guess is too low
    if (MyGuess < Number)
        LowEnd = MyGuess;
        fprintf('==> Hint: Too low!\n');
    % 2. guess is too high    
    elseif (MyGuess > Number)
        HighEnd = MyGuess;
        fprintf('==> Hint: Too high!\n');
    % 3. right on   
    else
        fprintf('==> CORRECT! (%d guesses)\n', Tries);
        break
    end
end