R while loop

R while loop

In this guide we will discuss about R while loop.

A while loop is a type of control flow statements which is used to iterate a block of code several numbers of times. The while loop terminates when the value of the Boolean expression will be false.

In while loop, firstly the condition will be checked and then after the body of the statement will execute. In this statement, the condition will be checked n+1 time, rather than n times.

The basic syntax of while loop is as follows:

while (test_expression) {  
   statement  
}  

Flowchart

Example 1:

v <- c("Hello","while loop","example")  
cnt <- 2  
while (cnt < 7) {  
   print(v)  
   cntcnt = cnt + 1  
}}  

Output:

Example 2: Program to find the sum of the digits of the number.

n<-readline(prompt="please enter any integer value: ")  
please enter any integer value: 12367906  
n <- as.integer(n)  
sum<-0  
while(n!=0){  
    sumsum=sum+(n%%10)  
    n=as.integer(n/10)  
}  
cat("sum of the digits of the numbers is=",sum)  

Output:

Example 3: Program to check a number is palindrome or not.

n <- readline(prompt="Enter a four digit number please: ")  
n <- as.integer(n)  
num<-n  
rev<-0  
while(n!=0){  
    rem<-n%%10  
    rev<-rem+(rev*10)  
    n<-as.integer(n/10)  
}  
print(rev)  
if(rev==num){  
    cat(num,"is a palindrome num")  
}else{  
    cat(num,"is not a palindrome number")  
}  

Output:

Example 4: Program to check a number is Armstrong or not.

num = as.integer(readline(prompt="Enter a number: "))  
sum = 0  
temp = num  
while(temp > 0) {  
    digit = temp %% 10  
    sumsum = sum + (digit ^ 3)  
    temp = floor(temp / 10)  
}  
if(num == sum) {  
    print(paste(num, "is an Armstrong number"))  
} else {  
    print(paste(num, "is not an Armstrong number"))  
}  

Output:

Example 5: program to find the frequency of a digit in the number.

num = as.integer(readline(prompt="Enter a number: "))  
digit = as.integer(readline(prompt="Enter digit: "))  
n=num  
count = 0  
while(num > 0) {  
        if(num%%10==digit){  
            countcount=count+1  
        }  
        num=as.integer(num/10)  
}  
print(paste("The frequency of",digit,"in",n,"is=",count))  

Output:

Next Topic : Click Here

Leave a Reply