How do I complete this script for below question? I have partially created the script: see it below the question.
1 view (last 30 days)
Show older comments
Write a script that asks for a series of numbers and calculates the sum and the mean. When the user enters a value of 0, the script stops and performs the calculation. For example:
Enter a number (type 0 to end) : 5
Enter a number (type 0 to end) : 6
Enter a number (type 0 to end) : 7
Enter a number (type 0 to end) : 8
Enter a number (type 0 to end) : 0
4 numbers entered. Sum=26. Mean=6.5.
% initialisation
num==0;
while num==0
num=input('Enter a number (type 0 to end): ');
end %end while loop
2 Comments
Image Analyst
on 9 Nov 2015
I'll fix the formatting for you this time, but please read this for next time: http://www.mathworks.com/matlabcentral/answers/13205-tutorial-how-to-format-your-question-with-markup
Answers (1)
Image Analyst
on 9 Nov 2015
Have an accumulator variable (not named sum, which is a built in function name):
% initialisation
num==0;
theSum = 0;
loopCounter = 0;
while num==0
num=input('Enter a number (type 0 to end): ');
if num == 0
break;
end
theSum = theSum + num;
loopCounter = loopCounter + 1;
end %end while loop
if loopCounter >= 1
fprintf('%d numbers entered. Sum=%f. Mean=%.1f\n',...
loopCounter, theSum, theSum/loopCounter);
else
fprintf('0 numbers entered.\n');
end
2 Comments
Image Analyst
on 9 Nov 2015
Correct (I didn't notice the errors he had in his existing code).
Without the break line, you'd have to subtract 1 from the loop counter after the loop exits.
See Also
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!