MATLAB Answers

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

Asked by Maureen Peters

### Maureen Peters (view profile)

on 12 Jun 2018
Latest activity Edited by Jan

### Jan (view profile)

on 12 Jun 2018
%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

Rik

### Rik (view profile)

on 12 Jun 2018
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.

Sign in to comment.

## 2 Answers

Answer by Anton Semechko

### Anton Semechko (view profile)

on 12 Jun 2018

Here is the script
sum(2:2:1000)

#### 0 Comments

Sign in to comment.

Answer by Jan

on 12 Jun 2018
Edited by Jan

### Jan (view profile)

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.

#### 0 Comments

Sign in to comment.