How do I make a for loop for summing up to specified integer

1 回表示 (過去 30 日間)
Joe810
Joe810 2015 年 6 月 18 日
コメント済み: Purushottama Rao 2015 年 6 月 19 日
How can I make a for loop for summing up integers starting at 0 and going to the integer the user inputs(user can choose any integer)
ex:
user inputs 3: 1+2+3
user inputs 6: 1+2+3+4+5+6

回答 (2 件)

Azzi Abdelmalek
Azzi Abdelmalek 2015 年 6 月 18 日
編集済み: Azzi Abdelmalek 2015 年 6 月 18 日
n=6
out=sum(1:n)
  2 件のコメント
Joe810
Joe810 2015 年 6 月 18 日
How will this work with a for loop?

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


Purushottama Rao
Purushottama Rao 2015 年 6 月 19 日
clc
k=input('Enter no');
sum=0;
for n=1:k
sum=sum+n;
end
disp(sum)
  1 件のコメント
Purushottama Rao
Purushottama Rao 2015 年 6 月 19 日
'For' loop is not necessary for whay you wanted to do. You can rather use input function along with sum. However since you were specific to use for loop, above code is given

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

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by