% Add user-input positive numbers until a negative is input
% then compute the average of the numbers
% We need to accumulate two things; the total of the values entered
% and the number of values entered.
clear
% total will accumulate the values
% n will count the number of values
total = 0;
n = 0;
% flag is used to trigger the exit from the while loop.
% flag is 0 as long as the user enters positive values.
% Once a negative value for t is entered, flag is set to 1.
% This will cause the loop to exit on the next pass.
flag = 0;
while (flag == 0)
t = input(' Input next value ');
if(t < 0)
flag = 1;
else
%
% Only increase the value of n if a positive value is entered for t
%
n = n + 1;
total = total + t;
end
end
% Wait until the loop terminates to compute the average because we won't
% have all the necessary information until the loop terminates.
avg = total/n;
ts = ['Total of values entered = ' num2str(total)];
disp(ts)
ts = ['Average of values entered = ' num2str(avg)];
disp(ts)