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).
Show older comments
I NEED THIS QUESTION ANSWER S = 1/2 N(N+1)
Accepted Answer
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);
Tarun Sangwan
on 25 Mar 2024
0 votes
%% 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
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
Categories
Find more on Structures 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!