R Tutorials
R Data Structures
R Graphics
R Statistics
R Examples
A for
loop is used for multiplication in sequence:
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 a for
loop we can create a set of statements, once per object in vector, matching members, lists, etc ..
Print every item in a list:
Print the number of dices:
The for loop does not require variable indexing to be pre-configured, such as for while
loops.
With a break
statement, we can stop the loop before it goes into all items:
Stop the loop at "cherry":
The loop will stop at "cherry" because we chose to end the loop using a break
statement where x is equal to "cherry" (x == "cherry"
).
With the next
statement, we can skip repeats without breaking the loop:
Skip "banana":
When the loop passes the "banana", it will jump and continue the loop.
To illustrate a practical example, suppose we are playing a game of Yahtzee!
Print "Yahtzee!" If the dice number is 6:
When the loop reaches values from 1 to 5, it prints "No Yahtzee" and its number. When it reaches a value of 6, it prints "Yahtzee!" and its number.
You can also have a loop inside the loop:
Print the adjective of each fruit in a list: