Loops


>> In this lecture we will study about the loops. There may be a situation when you need to execute a block of code several number of times. In general, statements are executed sequentially. The first statement in a function is executed first, followed by the second, and so on. Programming languages provide various control structures that allow for more complicated execution paths.


A loop statement allows us to execute a statement or group of statements multiple times and following is the general form of a loop statement in most of the programming languages.


MATLAB provides following types of loops to handle looping requirements.


1. While loop.


2. For loop.


3. Nested loop.



1. While loop:


An expression is true when the result is nonempty and contains all nonzero elements (logical or real numeric). Otherwise, the expression is false. The while loop repeatedly executes statements until the condition is true.


Syntax:


The syntax of a while loop in MATLAB is:


while <expression>


<statements>


end



Example:




2. For loop:


A for loop is a repetition control structure that allows you to efficiently write a loop that needs to execute a specific number of times.


Syntax:


The syntax of a for loop in MATLAB is:


for index = values


<program statements>

          ...
end


Examples:












3. Nested loop:


MATLAB allows to use one loop inside another loop. Following section shows few examples to illustrate the concept.


Syntax:


The syntax for a nested for loop statement in MATLAB is as follows:


for m = 1:j


<statements>;


end

end


The syntax for a nested while loop statement in MATLAB is as follows:


while <expression1>


while <expression2>


<statements>


end


end


Example:


for i=2:100


for j=2:100


if(~mod(i,j)) 


break; % if factor found, not prime


end 


end


if(j > (i/j))

fprintf('%d is prime\n', i);


end



end


the solution will be





Loop Control Statements:


Loop control statements change execution from its normal sequence. When execution leaves a scope, all automatic objects that were created in that scope are destroyed.



MATLAB supports the following control statements.

a. Break statement.


b. Continue statement.



a. Break statement:


The break statement terminates execution of for or while loop. Statements in the loop that appear after the break statement are not executed.



In nested loops, break exits only from the loop in which it occurs. Control passes to the statement following the end of that loop.

Example:




b. Continue statement:


The continue statement is used for passing control to next iteration of for or while loop. The continue statement in MATLAB works somewhat like the break statement. Instead of forcing termination, however, 'continue' forces the next iteration of the loop to take place, skipping any code in between.


Example: