Break statement
Most of the languages provide functionality using which we can stop the iteration of for-loop at the moment and come out of the current for-loop scope. For this purpose, we have the “break” statement in R. Break statement in R is the same as the break statement in C or C++.
Example 1: In the below program the flow of control of the outer for-loop comes out of the scope once the value of number1 reaches towards 2.
R
# R program to illustrate the working # of break statement in nested for-loop # Iterating over 1 to 5 in outer for-loop for (number1 in 1:5) { # If number1 is equal to 2 # then break the flow of control # and come out of the outer loop if (number1 == 2) break # Iterating over 1 to 5 in inner for-loop for (number2 in 1:5) { # Print the sum of number1 and number2 print ( paste (number1, "+" , number2, "=" , number1 + number2)); } } |
Output:
Example 2: In the below program the flow of control of the inner for-loop comes out of the scope once the value of number2 reaches towards 2.
R
# R program to illustrate the working of # break statement in nested for-loop # Iterating over 1 to 5 in the outer for-loop for (number1 in 1:5) { # Iterating over 1 to 5 in the inner for-loop for (number2 in 1:5) { # If number2 is equal to 2 then stop # the flow of control # and come out of the inner for-loop at the moment if (number2 == 2) break # Print the sum of number1 and number2 print ( paste (number1, "+" , number2, "=" , number1 + number2)); } } |
Output:
How to Create a Nested For Loop in R?
A loop in a programming language is a sequence of instructions executed one after the other unless a final condition is met. Using loops is quite frequent in a program.
Contact Us