Sum of integers up to n using a while loop

37 ビュー (過去 30 日間)
Will Murphy
Will Murphy 2020 年 2 月 15 日
コメント済み: Will Murphy 2020 年 2 月 15 日
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 2020 年 2 月 15 日
Are we supposed to see why it doesn't work now?

サインインしてコメントする。

採用された回答

JESUS DAVID ARIZA ROYETH
JESUS DAVID ARIZA ROYETH 2020 年 2 月 15 日
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 件のコメント
Turlough Hughes
Turlough Hughes 2020 年 2 月 15 日
Line 4 is
while k <= n
k <= n is checking if the current value of k is less than or equal to n. If k is less than or equal to n then the condition is true and another iteration of the loop is implemented, if it is false, the loop is terminated.
Every time the loop is iterated, the value of k increases by 1 due to line 6
k = k+1;
It might help you to see the values as the loop progresses by running the following code:
s = 0;
k = 1;
n = 10 ;
while k <= n
fprintf('Iteration Number: %d\n\nValues at start of iteration \nk = %d \ns = %d\n',k,k,s)
s=s+k;
k=k+1;
fprintf('Values at end of iteration \nk = %d \ns = %d\n\n\n',k,s)
end
Will Murphy
Will Murphy 2020 年 2 月 15 日
Ah okay, I had misinterpreted the symbols. All cleared up now, thanks for the help.

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeLogical についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by