Summarizing numbers using a loop
3 views (last 30 days)
Show older comments
Im trying to get the hang of matlab and one exercise i found was to summarize all integers 1-100. It is too easy just using the sum function but my loop won't work.
n=0;
sum=0;
if n<101 %if n is less than 101 (i wan't to include 100) - do the following:
n=n+1; %add 1 to n
sum=sum+n; %add n to sum
end
sum %display sum
end
I get sum=1, why?
0 Comments
Answers (1)
Geoff Hayes
on 4 Sep 2017
Edited: Geoff Hayes
on 4 Sep 2017
Olle - your code seems to be missing the for loop so I suspect that is the reason that you are only getting a value of 1. Consider the following
mySum = 0;
for k = 1:100
mySum = mySum + k;
end
We iterate over each integer from 1 to 100 and add that value to our running total (the mySum variable). (You were using a variable named sum to do the same thing. I recommend against this since sum is a built-in MATLAB function and "replacing" the function with your local variable will cause unexpected errors if you then choose to use the sum function.)
See Also
Categories
Find more on Loops and Conditional Statements 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!