w3resource

Reverse number using While loop in R

R Programming: Control Structure Exercise-16 with Solution

Write a R program to find the reverse of a given number using a while loop.

Sample Solution :

R Programming Code :

# Define a function to find the reverse of a given number using a while loop
reverse_number <- function(number) {
    # Initialize variables
    reverse <- 0
    
    # Iterate until the number becomes 0
    while (number != 0) {
        # Extract the last digit of the number
        digit <- number %% 10
        
        # Append the digit to the reverse number
        reverse <- reverse * 10 + digit
        
        # Remove the last digit from the number
        number <- number %/% 10
    }
    
    # Return the reverse of the given number
    return(reverse)
}

# Test the function with an example input
number <- 12345678  # Example number to find its reverse
reversed_number <- reverse_number(number)

# Print the result
cat("Reverse of", number, "is:", reversed_number, "\n")

Output:

Reverse of 12345678 is: 87654321           

Explatnaion:

In the exercise above,

  • The "reverse_number()" function takes a positive integer 'number' as input and finds its reverse.
  • It initializes 'reverse' to 0.
  • Using a while loop, it iterates until the 'number' becomes 0.
  • In each iteration, it extracts the last digit of the 'number' using the modulus operator (%%) and appends it to the 'reverse' number by multiplying 'reverse' by 10 and adding the extracted digit.
  • After appending all digits, it removes the last digit from the 'number' using integer division (%/%).
  • Once the 'number' becomes 0, the reverse of the given number is obtained.

R Programming Code Editor:



Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Check Perfect number using While loop in R.
Next: Power Calculation with Recursion in R.

Test your Programming skills with w3resource's quiz.

What is the difficulty level of this exercise?



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/r-programming-exercises/control-structure/r-programming-control-structure-exercise-16.php