Write a script to calculate the sum of even numbers from between 1 to 1000
Show older comments
%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 Comment
Answers (2)
Anton Semechko
on 12 Jun 2018
Here is the script
sum(2:2:1000)
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.
Categories
Find more on Get Started with MATLAB in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!