I need help writing a program to pick the largest number in a list
Show older comments
I was given:
clc;
n=input('how many numbers are in your list?');
for i=1:n
y=['enter a number', num2str(i)];
disp (y)
x(i)=input('');
end
and the list of numbers to plug in. I need to finish the program so it will choose the largest from my list. This is what I have so far:
if x(i)<=y
[newx,newy]=swap (x,y)
newx=y
newy=x
else x(i)>y
disp('The largest number in the list is')
end
This program runs but does not give me a single value. What should i do to fix it?
12 Comments
Jan
on 12 Feb 2017
You forgot to ask a question. There is the max command, but you can write a loop also, which compares all numbers with the largest value found already. Try to start, post the code and ask a specific question. This is the best way to learn.
justin simmons
on 12 Feb 2017
Walter Roberson
on 12 Feb 2017
Hint:
Suppose you have looked at the first 5 elements and found the largest of them. How would you extend that to find the largest of the first 6 elements?
justin simmons
on 12 Feb 2017
Walter Roberson
on 12 Feb 2017
Edited: Walter Roberson
on 12 Feb 2017
Suppose I tell you a list of numbers. What is your normal procedure for finding out which one of the list is the largest? I don't mean in programming: how do you do it?
For example, is your usual method to write all of the numbers on individual pieces of paper, and put the papers in a hat, and take out one at random, remember it if it is the largest you have seen so far, throw it back in the hat, take out one at random, remember it if it is the largest seen so far, throw back in the hat, and keep doing that random selection 200 times and then decide that statistically speaking you surely have pulled out the largest number by now?
justin simmons
on 12 Feb 2017
Walter Roberson
on 12 Feb 2017
No, no, the question is how YOU do this. I doubt that YOU use a hat, for example. You might use a bowl or a basket or a pot, but you probably do not use a hat. What do YOU do? And what would you do if there were more than 200 numbers given?
justin simmons
on 12 Feb 2017
Walter Roberson
on 12 Feb 2017
But that is not what YOU would do for less than 200 numbers?
justin simmons
on 12 Feb 2017
Edited: justin simmons
on 12 Feb 2017
Walter Roberson
on 13 Feb 2017
Computers cannot "just look", but they can use the same kind of procedure you describe.
justin simmons
on 13 Feb 2017
Accepted Answer
More Answers (0)
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!