HTML tutorial
CSS3 tutorial
Bootstrap tutorial
JavaScript tutorial
JQuery tutorial
AngularJS tutorial
React tutorial
NodeJS tutorial
PHP tutorial
Python tutorial
Python3 tutorial
Django tutorial
Linux tutorial
Docker tutorial
Ruby tutorial
Java tutorial
C tutorial
C ++ tutorial
Perl tutorial
JSP tutorial
Lua tutorial
Scala tutorial
Go tutorial
ASP.NET tutorial
C # tutorial
A for loop is used for iterating over a sequence
A for
loop is used for iterating over a sequence:
for (x in 1:10) {
print(x)
}
This is less like the for
keyword in other programming languages, and works more like an iterator
method as found in other object-orientated programming languages.
With the for
loop we can execute a set of statements, once for each item in a vector,
array, list, etc..
Print every item in a list:
fruits <- list("apple", "banana", "cherry")
for (x in fruits) {
print(x)
}
Print the number of dices:
dice <- c(1, 2, 3, 4, 5, 6)
for (x in dice) {
print(x)
}
The for
loop does not require an indexing variable to set beforehand, like with while
loops.
With the break
statement, we can stop the loop before it has looped through all the items:
Stop the loop at "cherry":
fruits <- list("apple", "banana", "cherry")
for (x in fruits) {
if (x == "cherry") {
break
}
print(x)
}
The loop will stop at "cherry" because we have chosen to finish the loop by using the break
statement when
x
is equal to "cherry" (x ==
"cherry"
).
With the next
statement, we can skip an iteration without terminating the loop:
Skip "banana":
fruits <- list("apple", "banana", "cherry")
for (x in fruits) {
if (x == "banana") {
next
}
print(x)
}
When the loop passes "banana", it will skip it and continue to loop.
If .. Else Combined with a For Loop
To demonstrate a practical example, let us say we play a game of Yahtzee!
Print "Yahtzee!" If the dice number is 6:
dice <- 1:6
for(x in dice) {
if (x == 6) {
print(paste("The dice number is", x, "Yahtzee!"))
} else {
print(paste("The dice number is", x, "Not Yahtzee"))
}
}
If the loop reaches the values ranging from 1 to 5, it prints "No Yahtzee" and its number. When it reaches the value 6, it prints "Yahtzee!" and its number.
You can also have a loop inside of a loop:
Print the adjective of each fruit in a list:
adj <- list("red", "big", "tasty")
fruits <- list("apple", "banana",
"cherry")
for (x in adj) {
for (y in fruits) {
print(paste(x, y))
}
}