Friday, November 27, 2020

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:

  1. while (test_expression) {  
  2.    statement  
  3. }  

Flowchart

R While Loop

Example 1:

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

Output

R While Loop

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

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

Output

R While Loop

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

  1. <- readline(prompt="Enter a four digit number please: ")  
  2. <- as.integer(n)  
  3. num<-n  
  4. rev<-0  
  5. while(n!=0){  
  6.     rem<-n%%10  
  7.     rev<-rem+(rev*10)  
  8.     n<-as.integer(n/10)  
  9. }  
  10. print(rev)  
  11. if(rev==num){  
  12.     cat(num,"is a palindrome num")  
  13. }else{  
  14.     cat(num,"is not a palindrome number")  
  15. }  

Output

R While Loop

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

  1. num = as.integer(readline(prompt="Enter a number: "))  
  2. sum = 0  
  3. temp = num  
  4. while(temp > 0) {  
  5.     digit = temp %% 10  
  6.     sumsum = sum + (digit ^ 3)  
  7.     temp = floor(temp / 10)  
  8. }  
  9. if(num == sum) {  
  10.     print(paste(num, "is an Armstrong number"))  
  11. } else {  
  12.     print(paste(num, "is not an Armstrong number"))  
  13. }  

Output

R While Loop

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

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

Output

R While Loop


No comments:

Post a Comment

How to DROP SEQUENCE in Oracle?

  Oracle  DROP SEQUENCE   overview The  DROP SEQUENCE  the statement allows you to remove a sequence from the database. Here is the basic sy...