MATLAB Answers

Sum of integers up to n using a while loop

조회 수: 271(최근 30일)
Hi, I've recently started coding as part of my uni maths course, however I am struggling very much with the learning curve.
I want to know how to sum all the positive numbers up to and including n by using a while loop.
From what I have gathered already I would use in the case of n = 10
s = 0
n = 10
while s < ((n + 1) * n / 2)
N = N + 1
s = s + N
end
disp(s)
What could I do to make this work? Any help would be greatly appreciated,
  댓글 수: 1
Matt J
Matt J 15 Feb 2020
Are we supposed to see why it doesn't work now?

댓글을 달려면 로그인하십시오.

채택된 답변

JESUS DAVID ARIZA ROYETH
try it yourself with a for (see documentation)
You can be guided by this example:
s = 0;
k=1;
n = 10 ;
while k <= n
s=s+k;
k=k+1;
end
disp(s)
In the end, the idea is that with practice you can do all this code in a line like this:
n=10
s=sum(1:n)
  댓글 수: 3
Will Murphy
Will Murphy 15 Feb 2020
Ah okay, I had misinterpreted the symbols. All cleared up now, thanks for the help.

댓글을 달려면 로그인하십시오.

추가 답변(0개)

태그

Community Treasure Hunt

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

Start Hunting!

Translated by