How to sum an array using a while loop?

조회 수: 2 (최근 30일)
Christian
Christian 2014년 11월 2일
댓글: Star Strider 2014년 11월 3일
So I have been attempting to add a 9 element 1x1 array using the while loop. I have failed miserably for over 3 hours. I attempted to use:
x=1:length(array)
sumx2=0
while sumx2<sum(array)
sumx2=sumx2+x(array)
end
at times I get numbers increasing on Matlab and they don't stop. Will you be kind enough to share your knowledge? Thank you in advance.

답변 (1개)

Star Strider
Star Strider 2014년 11월 2일
I didn’t want to disrupt your code too much, but I had to do some editing:
array = rand(1,9); % Test Array
x=1:length(array); % You probably Don’t Need This
sumx2=0
k = 1; % Add Counter Variable
while k <= length(array)
sumx2=sumx2+array(k); % Add Element Of ‘array’ to ‘sum2’
k = k+1; % Increment Counter
end
You were on the correct track, but weren’t implementing your idea correctly. You need to address each element of ‘array’ individually to add it incrementally to ‘sum2’.
  댓글 수: 2
Christian
Christian 2014년 11월 3일
Thank you!
Well I solved my problem actually haha. What I did was:
N=numel(x)
i=0
sumx2=0
while i<N
i=i+1
sumx2=sumx2+x(i)
end
So that's what I did and it worked! Is this a different method? Thanks!
Star Strider
Star Strider 2014년 11월 3일
My pleasure!
It’s a different method, yes, and is probably as efficient as my code.
If you’re just getting started with programming, you’ll find that with the exception of the very simplest programs, there are a number of different ways of solving the same problem. Speed of execution is usually the criterion for deciding the ‘best’ method, but such things as memory utilisation can also be the deciding factor.

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by