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
}
  1. variable - The values in the variable takes on a specified sequence during each iteration.
  2. sequence - Declares a sequence that can be a vector, list, or other iterable data structures.

Example

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

Example

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.
  1. break: exits the loop permenently
  2. next: skips the execution of the loop for current iteration and moves to next iteration.

Example

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
R Nested Loop
Using break and next statements

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 js

Example 1 Example 2 Example 3 Example 4 Example 5


Quiz


FEEDBACK