R Program to convert decimal into binary using recursion


February 5, 2023, Learn eTutorial
2409

What are decimal numbers and binary numbers?

  • Decimal numbers: are the numbers with the base 10, which means we can represent that number using the numbers from 0 to 9. 
  • Binary numbers: are numbers with the base 2 which means we have only 0 and 1 to represent a number.

How to convert a decimal number into binary by using recursion in R?

In this R program to convert a decimal number into binary, Accept the user input which we need to convert to binary, and give the number directly to the function convert_to_binary(), Check if the given decimal number is greater than 1. Conversion into binary is done by dividing the number successively by 2 and the remainder is printed in reverse order which will be the binary of that decimal.

What is recursion?

Recursion is a process by which a function will call itself continuously until a condition is met. The function call may be direct or indirect.

ALGORITHM

STEP 1: Call function convert_to_binary()

STEP 2: Pass the decimal number which needs to be converted to binary as decnum to the function.

STEP 3: inside the function check if the given number is greater than 1, if yes call function convert_to_binary() again with decnum/2 as the argument

STEP 4: divide the number decnum successively by 2 and print the remainder

R Source Code

                                          convert_to_binary <- function(decnum) {
if(decnum > 1) {
convert_to_binary(as.integer(decnum/2))
}
cat(decnum %% 2)
}
convert_to_binary(52)
                                      

OUTPUT

110100