Write a script to calculate the sum of even numbers from between 1 to 1000

168 ビュー (過去 30 日間)
Maureen Peters
Maureen Peters 2018 年 6 月 12 日
編集済み: Jan 2018 年 6 月 12 日
%program to cal the sum of %even no from between 1 to %1000
Num=input('enter integer no')
Counter=1
Increase counter by 1
Until
Counter=1000
Sum= counter + counter
Disp('sum')
End
  1 件のコメント
Rik
Rik 2018 年 6 月 12 日
This is probably a homework assignment, aimed at learning to use the for and if functions. If that is the case, the answer by Anton is not valid, but you shouldn't be using it anyway. You can find guidelines for posting homework on this forum here.

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

回答 (2 件)

Anton Semechko
Anton Semechko 2018 年 6 月 12 日
Here is the script
sum(2:2:1000)

Jan
Jan 2018 年 6 月 12 日
編集済み: Jan 2018 年 6 月 12 日
Concerning you pseudo-code:
% There is no need to enter a number.
% Num = input('enter integer no')
% You want the *even* numbers, so start at 2:
Counter = 2
Then an initialization of "Sum" is missing:
Sum = 0;
% Increase counter by *2* (not by 1)
% Until Counter=1000
while Counter <= 1000
Sum = Sum + Counter; % Matlab is case-sensitive
Counter = Counter + 2; % Increase the Counter
end
disp(Sum) % disp('Sum') would show the string 'Sum'
A for loop is usually shorter:
s = 0;
for k = 2:2:1000
s = s + k;
end
disp(s)
Anton posted an even nicer solution.
But do you remember Gauss? You do not need to add all elements, because you can get the result much cheaper. The sum of N even numbers is N*(N+1). Here N is 1000/2, but in the general case:
function S = SumOfEven(X)
N = floor(X / 2); % round() to consider odd value of X
S = N * (N + 1);
end
No loops needed :-)
Welcome to Matlab. This forum does not solve homework questions usually for good reasons. But your pseudo-code was very far away from Matlab, such that I wanted to give you a short overview to get in touch with this language. To solve the coming homework questions or to learn Matlab in general, read the "Getting Started" chapters of the documentation and launch the free MATLAB Onramp.

カテゴリ

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

Community Treasure Hunt

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

Start Hunting!

Translated by