Summation of numbers using prompts

7 views (last 30 days)
Mark Coughlin
Mark Coughlin on 26 Apr 2020
Edited: Sindar on 27 Apr 2020
I want the program to prompt the user for the value n (the number of values to be added together). I then want the program to prompt the user n times for a number, for it to the add these numbers together and finally print the result. Any help would be appreciated, thank you! This is my code so far:
function sumnnums(n);
prompt='Enter the value of n: ';
n=input(prompt);
sum=0;
for i=1:n
prompt='Enter a number: ';
x(i)=input(prompt);
end
sum=sum+x;
formatSpec='The sum of the numbers is %6.4f\n';
fprintf(formatSpec,x(i));
end

Accepted Answer

Sindar
Sindar on 27 Apr 2020
Edited: Sindar on 27 Apr 2020
Two errors:
  • The function should not have n as an argument. Wait to ask the user
  • don't use "sum" as a variable name; it's a function
  • if you want to do "sum=sum+x" it needs to be in the loop and x needs to be a scalar. But, there's no reason to do it like that since you're already storing the results in an array. Just do this:
mysum = sum(x);
  • if you've calculated the sum, why are you printing x(i)?

More Answers (0)

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!