Jump Statements in Loop
We use a jump statement in loops to terminate the loop at a particular iteration or to skip a particular iteration in the loop. The two most commonly used jump statements in loops are:
- Break Statement: The break keyword is a jump statement that is used to terminate the loop at a particular iteration.
Example:
R
# R program to illustrate # the use of break statement # using for loop # to iterate over a sequence for (val in 1: 5) { # checking condition if (val == 3) { # using break keyword break } # displaying items in the sequence print (val) } |
Output:
[1] 1 [1] 2
In the above program, if the value of val becomes 3 then the break statement will be executed and the loop will terminate.
- Next Statement: The next keyword is a jump statement which is used to skip a particular iteration in the loop.
Example:
R
# R program to illustrate # the use of next statement # using for loop # to iterate over the sequence for (val in 1: 5) { # checking condition if (val == 3) { # using next keyword next } # displaying items in the sequence print (val) } |
Output:
[1] 1 [1] 2 [1] 4 [1] 5
In the above program, if the value of Val becomes 3 then the next statement will be executed hence the current iteration of the loop will be skipped. So 3 is not displayed in the output.
As we can conclude from the above two programs the basic difference between the two jump statements is that the break statement terminates the loop and the next statement skips a particular iteration of the loop.
Loops in R (for, while, repeat)
In R programming, we require a control structure to run a block of code multiple times. Loops come in the class of the most fundamental and strong programming concepts. A loop is a control statement that allows multiple executions of a statement or a set of statements. The word ‘looping’ means cycling or iterating.
A loop asks a query, in the loop structure. If the answer to that query requires an action, it will be executed. The same query is asked again and again until further action is taken. Any time the query is asked in the loop, it is known as an iteration of the loop. There are two components of a loop, the control statement, and the loop body. The control statement controls the execution of statements depending on the condition and the loop body consists of the set of statements to be executed.
In order to execute identical lines of code numerous times in a program, a programmer can simply use a loop.
Contact Us