Open In App

Print the Elements of a Vector using Loop in R

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
}

Example 1: while loop to print the elements of a vector




vector <- c(1, 2, 3, 4, 5)
 
i <- 1
 
while (i <= length(vector)) {
  cat(vector[i], " ")
  i <- i + 1
}

Output:



1  2  3  4  5  

Example 2: while loop to print the elements of a string value vector




vector <- c("apple", "banana", "cherry", "date")
 
i <- 1
 
while (i <= length(vector)) {
  cat(vector[i], " ")
  i <- i + 1
}

Output:

apple  banana  cherry  date  

Example 3 Using a while loop with indexing




vector <- c(10, 20, 30, 40, 50)
index <- 1
 
while (index <= length(vector)) {
  print(vector[index])
  index <- index + 1
}

Output:

[1] 10
[1] 20
[1] 30
[1] 40
[1] 50

Example 4 Using a while loop with vector slicing




vector <- c(10, 20, 30, 40, 50)
index <- 1
 
while (index <= length(vector)) {
  print(vector[1:index])
  index <- index + 1
}

Output:

[1] 10
[1] 10 20
[1] 10 20 30
[1] 10 20 30 40
[1] 10 20 30 40 50


Article Tags :