Open In App

repeat loop to print the elements of a vector.

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 repeat loop. In R programming, loops are essential constructs that allow us to repeat a set of instructions multiple times. The repeat loop is one such construct that repeatedly executes a block of code until a certain condition is met. This loop is particularly useful when you want to iterate over elements without knowing the exact number of iterations in advance. In this article, we will explore how to use the repeat loop to print the elements of a vector and understand its step-by-step implementation.

Syntax:

vector <- c(...)  # Replace ... with the vector elements
i <- 1
repeat {
# Code to execute
}

Example 1:




my_vector <- c(1, 2, 3, 4, 5)
 
# Using repeat loop to print vector elements
i <- 1
repeat {
  print(my_vector[i])
  i <- i + 1
  if (i > length(my_vector)) {
    break
  }
}

Output:



[1] 1
[1] 2
[1] 3
[1] 4
[1] 5

Example 2:




fruits <- c("Apple", "Banana", "Orange", "Grapes")
 
# Using repeat loop to print vector elements
i <- 1
repeat {
  cat("Fruit:", fruits[i], "\n")
  i <- i + 1
  if (i > length(fruits)) {
    break
  }
}

Output:

Fruit: Apple 
Fruit: Banana
Fruit: Orange
Fruit: Grapes

Example 3:




cat("\nUsing a repeat loop:\n")
index <- 1
repeat {
  if (index > length(my_vector)) {
    break
  }
  print(my_vector[index])
  index <- index + 1
}

Output:



[1] 1
[1] 2
[1] 3
[1] 4
[1] 5

Article Tags :