repeat loop in R


Repeat loop in R is used to iterate over a block of code multiple number of times. And also it executes the same code again and again until a break statement is found.

Repeat loop, unlike other loops, doesn’t use a condition to exit the loop instead it looks for a break statement that executes if a condition within the loop body results to be true. An infinite loop in R can be created very easily with the help of the Repeat loop. The keyword used for the repeat loop is 'repeat'.

Syntax:
repeat {
 commands 
 if(condition) { 
 break } 
}

# R program to illustrate repeat loop

result <- 1
# test expression
repeat {
print(result)
# update expression
result = result + 1
# Breaking condition
if(result > 5) {
break
}
}

output:
[1] 1
[1] 2
[1] 3
[1] 4
[1] 5

#checking for prime
n <- 21
b <- a/2
flag <- 0
i <- 2
repeat
{
if ((n %% i)== 0)
{
flag <- 1
break
}

if (i>b) {
break}

    i=i+1
}
if (flag == 1)
{
print("composite")
}else{
print("prime")
}

Comments

Popular posts from this blog

Programming in R - Dr Binu V P

Introduction

R Data Types