R while loop is a type of loop that is used to iterate a block of code multiple numbers of times to control the flow of statements. The while loop terminates when the value of the Boolean expression will be false.
In a while loop, first of all, conditions will be checked and then the body of the statement will run. In this statement, the condition will be checked n+1 time instead of n times.
The generic syntax of the while loop is given below:
Flowchart of R while loop
The following code will print (“Welcome” “to” “Tutorials Art”) 5 times.
v <- c("Welcome","to","Tutorials Art") c <- 4 while (c < 9) { print(v) c = c + 1 }
Output:
The following code will calculate the sum of the given number of digits.
n <- 67449 s <-0 while(n!=0){ s=s+(n%%10) n=as.integer(n/10) } cat("sum of the digits=",s)
Output:
The following code will check whether the given number is Armstrong or not.
n = 345 s = 0 t = n while(t > 0) { d = t %% 10 s = s + (d ^ 3) t = floor(t / 10) } if(n == s) { print(paste(n, "is Armstrong")) } else { print(paste(n, "is not Armstrong")) }
Output:
The following code will check the frequency of 3 in the given number.
num = 123453456 d = 3 n=num c = 0 while(num > 0) { if(num%%10==d){ c=c+1 } num=as.integer(num/10) } print(paste("The frequency of",d,"in",n,"is=",c))
Output: