What is the main purpose of the R while Loop?
a) To execute a block of code repeatedly as long as a specified condition is TRUE
b) To iterate over elements of a vector
c) To define a function in R
d) To initialize variables
Answer:
a) To execute a block of code repeatedly as long as a specified condition is TRUE
Explanation:
The while
loop in R is a control structure used to execute a block of code repeatedly as long as a specified condition remains TRUE
. It is particularly useful when the number of iterations is not known in advance and should continue until a certain condition changes.
# Example of a while loop
i <- 1
while (i <= 5) {
print(i)
i <- i + 1
}
# Output:
# [1] 1
# [1] 2
# [1] 3
# [1] 4
# [1] 5
In this example, the loop starts with i
equal to 1 and continues to execute as long as i
is less than or equal to 5. In each iteration, i
is incremented by 1, and the loop prints the current value of i
.
The while
loop is ideal for situations where the continuation of the loop depends on a dynamic condition that may change during execution.