I am very new to MATLAB, so bear with me please.
I'm working on a school assignment regarding while loops and I am required to print a tally of all entered x values after the loop has ended, I have no clue how to do that however.
This is the assignment:
- Using different variable names than in the examples above, write a script to let the user type in values from the keyboard and sum them up. This time make the script only total up zeroes or negative values. If a positive value is entered the script should stop at that time. Or, if a negative value less than 500, such as -501 is entered, the script is to stop. When the script stops, give the tally, and in a separate statement indicate what caused the program to end.
This is an example of what should show up after the loop has ended:
-491
-12
0
Total = -503
A positive value of 5 was entered and stopped the summation.
(Or, a value of -682 was entered and stopped the summation.)
This is what I have:
clear
clc
fprintf(' This script will take an x value, as long as it is larger than -501,')
fprintf('\n and less than 1, and will add it to the previous x value.\n\n')
sum = 0;
a = -500;
x = input(' Enter a value greater than -501 and less than 1: ');
while ( 0 >= x ) && ( x >= a )
sum = sum + x;
x = input(' Enter another value greater than -501 and less than 1: ');
end
fprintf( 'Total = ')
fprintf( '%.f' , sum)
if ( x > 0)
fprintf('\n\nLoop ended, a positive value of ')
fprintf("%.f" , x)
fprintf(' was entered \n\n')
end
if ( x < a )
fprintf(' Loop ended, a negative value of ')
fprintf("%.f" , x)
fprintf(' was entered \n\n')
end