how do i give the user the option to stop making an input? while loops program.

I am supposed to create a program where i will continuously have the user input a grade for exam scores until they decide they want to stop. I've made this program so far but the way i set it up so it can stop (grade == 0) still counts the 0 in the end as the total amount of grades entered but i dont want it to do that. is there a better way giving the user an option to stop?
x = [];
loop = 1;
count = 0;
while (loop)
grade = input('Enter a grade: ');
count = count + 1
x = [x;grade];
if grade == 0
break
end
endwhile
fprintf('%g grades were entered.\n',count);

Answers (1)

Check the value of grade immediately after the user inputs it, and only update count and x if the loop should continue:
x = [];
loop = 1;
count = 0;
while (loop)
grade = input('Enter a grade: ');
if grade == 0
break
end
count = count + 1
x = [x;grade];
end
fprintf('%g grades were entered.\n',count);
What if someone scored a 0?

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Asked:

on 16 Apr 2020

Answered:

on 16 Apr 2020

Community Treasure Hunt

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

Start Hunting!