R Lang

R Program to reverse a number1 min read

In this program, You will learn how to reverse a number in R.

Example: How to reverse a number in R




This code defines a function in the R programming language that reverses the digits of a number. The function takes a single integer as input, stored in the variable n, and returns the reversed number.

The function begins by initializing a variable rev to 0. It then enters a loop that continues as long as n is greater than 0. Inside the loop, the function extracts the last digit of n by taking the remainder of n divided by 10 and assigns it to a variable r. It then adds r to the end of rev by multiplying rev by 10 and adding r, and updates n by dividing it by 10 and taking the integer part of the result.

When the loop completes, the function prints the reversed number using the print function and the paste function to concatenate strings.

You may also like: R Lang Exmaples

To run this code and see the output, you can follow these steps:

  1. Open RStudio or another R environment.
  2. Type the code into the R console or source it from a file using the source function.
  3. Call the function by typing its name and passing a number as an argument, e.g. reverse_number(123).
  4. The function will print the reversed number to the console.

For example, if you call the function with the argument 123, the output will be:

Reverse number is : 321

Leave a Comment