450 views (last 30 days)

%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

Jan
on 12 Jun 2018

Edited: Jan
on 12 Jun 2018

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.

Sign in to comment.

Sign in to answer this question.

Opportunities for recent engineering grads.

Apply Today
## 1 Comment

## Direct link to this comment

https://www.mathworks.com/matlabcentral/answers/405294-write-a-script-to-calculate-the-sum-of-even-numbers-from-between-1-to-1000#comment_577868

⋮## Direct link to this comment

https://www.mathworks.com/matlabcentral/answers/405294-write-a-script-to-calculate-the-sum-of-even-numbers-from-between-1-to-1000#comment_577868

Sign in to comment.