Clear Filters
Clear Filters

Write program by For loop, how can I stop

2 views (last 30 days)
Hi guys, I have a program, I use for loop, the answer is right , but I want to stop on the first negative answer. This is my program
A=[40 47 50 60 70 75 80 80 90 55];
B(1)=70;
C(1)=60;
for k=1:9;
C(k+1)= B(k)+C(k)-A(k);
B(k+1)= A(k);
if C(k+1)>=40
B(k+1)=0
k=k+1
end
end
C=C
The answer is 60 90 43 -7 -17 -27 -32 -37 -37 -47
How can I stop the answer on -7
Thank you

Accepted Answer

Matt Fig
Matt Fig on 20 Oct 2012
A=[40 47 50 60 70 75 80 80 90 55];
B(1)=70;
C(1)=60;
for k=1:9;
C(k+1)= B(k)+C(k)-A(k);
if C(k+1)<0,break,end % Stops the loop.
B(k+1)= A(k);
if C(k+1)>=40
B(k+1)=0
k=k+1
end
end

More Answers (0)

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Tags

Products

Community Treasure Hunt

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

Start Hunting!