![]() |
VOOZH | about |
A while loop is a fundamental control structure in programming that allows us to repeatedly execute a block of code as long as a specified condition remains true. It's often used for tasks like iterating over elements in a data structure, such as printing the elements of a vector. The loop continues to execute until the condition evaluates to false.
In this article, we will discuss how to print the elements of a vector with its working example in the R Programming Language using R while loop.
Syntax:
vector <- c(...) # Replace ... with the vector elements
i <- 1
while (i <= length(vector)) {
cat(vector[i], " ")
i <- i + 1
}
Output:
1 2 3 4 5
Output:
apple banana cherry date
Output:
[1] 10
[1] 20
[1] 30
[1] 40
[1] 50
while (index <= length(vector)) { ... }: This line starts a while loop. The loop will continue executing as long as the condition index <= length(vector) is TRUE. This ensures that the loop will iterate through the vector's elements until the index reaches the vector's length.print(vector[index]): Inside the loop, this line prints the element of the vector at the current index.index <- index + 1: After printing the element, this line increments the index by 1. This prepares the loop for the next iteration, moving to the next element in the vector.Output:
[1] 10
[1] 10 20
[1] 10 20 30
[1] 10 20 30 40
[1] 10 20 30 40 50
while (index <= length(vector)) { ... }: This line starts a while loop. The loop will continue executing as long as the condition index <= length(vector) is TRUE. print(vector[index]): Inside the loop, this line prints the element of the vector at the current index.