Write a MATLAB script file that calculates the sum of first n natural numbers (the program could prompt the user for the number n). The program must use a “for” or “while” loop to accomplish this, and must NOT use the ready formula s = 1 2 n (n + 1).
252 views (last 30 days)
Show older comments
I NEED THIS QUESTION ANSWER S = 1/2 N(N+1)
0 Comments
Accepted Answer
Sara Boznik
on 16 Aug 2020
That is easy.
n=input('n:')
sum=0;
for i=1:n
sum=sum+i
end
2 Comments
Image Analyst
on 16 Aug 2020
Edited: Image Analyst
on 16 Aug 2020
sum is a built-in function name. Use another name like "theSum" so as to not blow away the built-in function. Also, Harsha is probably not allowed to turn in Sara's solution as his own. And we're not supposed to give full solutions for homework problems so the poster won't get in trouble for cheating.
Sara Boznik
on 16 Aug 2020
yes, I usually use the name in my own language. so I dont have trouble with function name. I used sum in this case that Harsha will understand what the coda means.
More Answers (2)
Mohammad Emaz Uddin
on 3 Feb 2021
clc;
clear;
close all;
n= input('Enter numbers: ');
sum=0;
for i=1:1:n
sum=sum+i;
end
disp (sum);
0 Comments
Tarun Sangwan
on 25 Mar 2024
%% using cell method
function b = addds(n)
g = cell(1,n)
for i = 1:n
g{1,i} = i
end
b = sum(g)
%%using recurssion
function v = sums(start,stop,gums)
if start == stop
gums = gums + start
else
gums = gums + start
sums(start+1,stop,gums)
end
v = gums
%%using for loop
for i = 1:n
sum = sum + i
1 Comment
DGM
on 25 Mar 2024
Edited: DGM
on 25 Mar 2024
The lack of formatting and line suppression is bad enough, but none of these are valid local functions. You can clearly test that and know that they don't work. Even if you declared the last function and closed all the open scopes, none of these examples work.
The first example is nonsense. The sum() function does not work like that on cell arrays, and even if it did, there would be no point in using a cell array instead of a plain numeric array.
The second example clearly doesn't work because the calls to sums() are simply discarded.
The third example clearly doesn't work because sum() is never declared as a variable. Until it is shadowed, sum() is a function, and calling sum() without any arguments will throw an error.
Why post answers that clearly don't work? This doesn't help anybody.
n = 100;
x = sum(1:n) % reference
b = sum1(n)
v = sum2(1,n,0)
s = sum3(n)
% using cell method
function b = sum1(n)
g = cell(1,n);
for k = 1:n
g{1,k} = k;
end
b = sum([g{:}]);
end
% using recurssion
function gums = sum2(start,stop,gums)
if start == stop
gums = gums + start;
else
gums = gums + start;
gums = sum2(start+1,stop,gums);
end
end
% using for loop
function s = sum3(n)
s = 0;
for k = 1:n
s = s + k;
end
end
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!