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).
273 ビュー (過去 30 日間)
古いコメントを表示
I NEED THIS QUESTION ANSWER S = 1/2 N(N+1)
0 件のコメント
採用された回答
Sara Boznik
2020 年 8 月 16 日
That is easy.
n=input('n:')
sum=0;
for i=1:n
sum=sum+i
end
2 件のコメント
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
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
2021 年 2 月 3 日
clc;
clear;
close all;
n= input('Enter numbers: ');
sum=0;
for i=1:1:n
sum=sum+i;
end
disp (sum);
0 件のコメント
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
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
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
参考
カテゴリ
Help Center および File Exchange で Data Distribution Plots についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!