0

I need to write a program that returns the largest number entered by a user. The user can enter as many numbers >= 0 as they want and when they enter a -1, the program will stop and return the largest number. I am really struggling to do this. So far, I have this:

validInput = false;
while (~validInput)
  fprintf('Enter a number >= 0 or a negative to quit.\n');
  num = input('Enter a number or -1 to quit: ');
  if(num == -1)
    validinput = true;
    counter = 0;
  elseif(num>=0)
    counter = counter+1;
  end;
  if(counter == 0)
    fprintf('No values entered!');
  else
    array = (counter);
     m = max(counter);
     disp(m);
  end
end``
3
  • 2
    You have validInput and validinput both. Matlab is case sensitive. And there are other problems as well...for instance setting counter to 0 if one enters -1, instead counter should be initialized to 0 before the while loop. And not storing num anywhere, but calling max(counter) for a scalar counter... And that's still not the end of it. Commented Sep 24, 2015 at 22:05
  • Ok I fixed those 2 things, but how do I read numbers greater than or equal to 0 into the array? Commented Sep 24, 2015 at 22:10
  • Check out @NKN's solution below. It makes use of the fact that -1<0, so it spares some checks. Commented Sep 24, 2015 at 22:11

2 Answers 2

1
enteredNumber = 0;
biggestNumber = 0;
while (enteredNumber ~= -1)
    enteredNumber = input('Enter a number : ');
    if enteredNumber > biggestNumber
        biggestNumber = enteredNumber;
    end
end
disp(['The biggest number entered is: ' num2str(biggestNumber)]);
Sign up to request clarification or add additional context in comments.

Comments

1

You don't need to limit it to positive numbers but to answer your question, you can do this. And remove the || in < 0 to allow the user to choose negative numbers.

num = [];

while (true)
    in = input('Enter a number or a non-numeric character to quit: ');

    if isempty(in) || ~isnumeric(in) || in < 0
        break
    end

    num(end+1) = in;
end

[M, INDEX] = max(num);

if ~isempty(num)
    disp(['The ', num2str(INDEX),' was the maximum entered value and was: ', num2str(M), '.'])
else
    disp('No value entered.')
end

2 Comments

I suggest renaming MAX to something else: a beginner might not realize that the capitalization is intentional, and they might redefine max later in another application.
That's true. I made the change.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.