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)
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

Answers (1)

Image Analyst
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
Thorsten
Thorsten on 9 Nov 2015
Edited: Thorsten on 9 Nov 2015
First line should read
num = 1;
and while condition should read
while num ~= 0
And you could rewrite the code without a break, if you like, since the while loop breaks if its condition is false.
Image Analyst
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.

Sign in to comment.

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!