break statement
It is used to exit from a loop. Example 1 : We will be making a row vector and will only modify the first 6 values using the break statement.
MATLAB
% making a row vector of 1x10, starting from 1 % and the next value is +10 of it's previous value v = [1:10:100]; % the value of i will move from 1 to 10 % with an increment of 1 for i = 1:10, % making the ith element in vector to 0 v(i) = 0; % if the condition is true the break statement % will execute and the loop will terminate if i == 6, break ; % end the if condition end ; % end the for loop end ; % displays the modified vector v disp(v) |
Output :
0 0 0 0 0 0 61 71 81 91
Example 2 : break statement with while loop :
MATLAB
% initializing the variable i with 1 i = 1; % the while condition is always true while true % display the value of i disp(i); % display the below content disp(" is less than 5"); % make an increment of 1 in value of i i = i + 1; % if the if condition is true loop will break if i == 5, break ; % end the if statement end ; % end the while end ; |
Output :
1 is less than 5 2 is less than 5 3 is less than 5 4 is less than 5
Loops (For and While) and Control Statements in Octave
Control statements are expressions used to control the execution and flow of the program based on the conditions provided in the statements. These structures are used to make a decision after assessing the variable. In this article, we’ll discuss control statements like the if statement, for and while loops with examples.