how do i average numbers on matlab/octave using for loops and no arrays. Beginner programmer.

9 views (last 30 days)
My task is to ask the user how many numbers they will like to average in my case im setting it up so it will be 5 numbers. (I think this part should be only up to the user but i dont really know how to set this up correctly) Then i will ask then to "enter a number" repeatedly depending on the amount of numbers they chose to average. lastly, the command window will display to them " the average for the (amount they chose) numbers you entered is....." . sounds basic enough but this is what i came up so far and it doesnt seem to be going where i need it to be. how can i fix this?
user = input('How many numbers would you like to average? ');
for num = 1:5
input('Enter a number: ')
end
fprintf('The average of the 5 numbers you entered is %.2f\n',average)

Answers (1)

David Hill
David Hill on 4 Apr 2020
You were close, just a few mistakes.
user = input('How many numbers would you like to average? ');
for num = 1:user
a(num)=input('Enter a number: ');
end
fprintf('The average of the 5 numbers you entered is %.2f\n',mean(a));
  1 Comment
Image Analyst
Image Analyst on 4 Apr 2020
Or, using the loop itself to compute the mean instead of the mean() function:
numNumbers = input('How many numbers would you like to average? ');
theSum = 0;
for k = 1: numNumbers
userPrompt = sprintf('Enter number %d (out of %d) : ', k, numNumbers);
a = input(userPrompt);
theSum = theSum + a;
end
average = theSum / numNumbers
fprintf('The average of the %d numbers you entered is %f.\n', numNumbers, average);

Sign in to comment.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!