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).

276 次查看(过去 30 天)
I NEED THIS QUESTION ANSWER S = 1/2 N(N+1)

采纳的回答

Sara Boznik
Sara Boznik 2020-8-16
That is easy.
n=input('n:')
sum=0;
for i=1:n
sum=sum+i
end
  2 个评论
Image Analyst
Image Analyst 2020-8-16
编辑:Image Analyst 2020-8-16
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
Sara Boznik 2020-8-16
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.

请先登录,再进行评论。

更多回答(2 个)

Mohammad Emaz Uddin
clc;
clear;
close all;
n= input('Enter numbers: ');
sum=0;
for i=1:1:n
sum=sum+i;
end
disp (sum);

Tarun Sangwan
Tarun Sangwan 2024-3-25
%% 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 个评论
DGM
DGM 2024-3-25
编辑:DGM 2024-3-25
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
x = 5050
b = sum1(n)
b = 5050
v = sum2(1,n,0)
v = 5050
s = sum3(n)
s = 5050
% 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

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Data Distribution Plots 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by