R For Loop
Used to iterate a block of code for a specific number of times.
Syntax
for (variable in sequence) {
# Code to be executed in each iteration
}
- variable - The values in the variable takes on a specified sequence during each iteration.
- sequence - Declares a sequence that can be a vector, list, or other iterable data structures.
for (i in 1:5) {
print(paste("Iteration:", i))
}
The above example used a sequence 1:5 which means it iterates the variable i from 1 to 5
during each iteration it executes the block of code in the for loop.
Nested For Loop
In R For loop inside a For loop i.e; Nested for loop can be used
for (i in 1:3) {
for (j in 1:2) {
print(paste("Iteration:", i, "-", j))
}
}
Using break and next
Used to alter the proper flow of execution in the loops and also in conditional statements.
- break: exits the loop permenently
- next: skips the execution of the loop for current iteration and moves to next iteration.
for (i in 1:10) {
if (i == 5) {
break # exit the loop when i is 5
}
if (i %% 2 == 0) {
next # skip even numbers
}
print(i)
}
Quick Recap - Topics Covered
R For Loop
Used to iterate a block of code for a specific number of times.
Syntax
for (variable in sequence) {
# Code to be executed in each iteration
}
- variable - the values in the variable takes on a specified sequence during each iteration.
- sequence - Declares a sequence that can be a vector, list, or other iterable data structures.
R Nested Loop
In R For loop inside a For loop i.e; Nested for loop can be used
Syntax:
for (i in 1:3) {
for (j in 1:2) {
print(paste("Iteration:", i, "-", j))
}
}
Using break and next statements
Used to alter the proper flow of execution in the loops and also in conditional statements.
- break: exits the loop permenently
- next: skips the execution of the loop for current iteration and moves to next iteration.
Practice With Examples in Compilers
The Concepts and codes you leart practice in Compilers till you are confident of doing on your own. A Various methods of examples, concepts, codes availble in our websites. Don't know where to start Down some code examples are given for this page topic use the code and compiler.
Example 1
Example 1
Example 2
Example 3
Example 4
Example 5
Quiz