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

조회 수: 152 (최근 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 CenterFile Exchange에서 MATLAB에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by