Download presentation
Presentation is loading. Please wait.
Published byElijah Wilson Modified over 9 years ago
2
There are two additional statements that can be used to control the operation of while loops and for loops: break statements continue statements
3
The break statement terminates the execution of a loop and passes control to the next statement after the end of the loop. An example of the break statement in a for loop is shown here. for ii = 1:5 if ii == 3; break; end fprintf('ii = %d\n',ii); end disp(['End of loop!']); When this program is executed, the output is » test_break ii = 1 ii = 2 End of loop!
4
If a continue statement is executed in the body of a loop, the execution of the current pass through the loop will stop, and control will return to the top of the loop. The controlling variable in the for loop will take on its next value, and the loop will be executed again. An example of the continue statement in a for loop is shown here. for ii = 1:5 if ii == 3; continue; end fprintf('ii = %d\n',ii); end disp(['End of loop!']); When this program is executed, the output is » test_continue ii = 1 ii = 2 ii = 4 ii = 5 End of loop!
5
It is possible for one loop to be completely inside another loop. If one loop is completely inside another one, the two loops are called nested loops. The following example shows two nested for loops used to calculate and write out the product of two integers. for ii = 1:3 for jj = 1:3 product = ii * jj; fprintf('%d * %d = %d\n',ii,jj,product); end
6
If a break or continue statement appears inside a set of nested loops, then that statement refers to the innermost of the loops containing it. For example, consider the following program: for ii = 1:3 for jj = 1:3 if jj == 3; break; end product = ii * jj; fprintf('%d * %d = %d\n',ii,jj,product); end fprintf('End of inner loop\n'); end fprintf('End of outer loop\n');
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.