Here we are explaining how to write an R program to convert a decimal number into binary by creating a recursion. Give the required number as an argument to the recursive function. Conversion into binary is done by dividing the number successively by 2 and the remainder is printed in reverse order.
Given below are the steps which are used in the R program to convert a decimal number into binary. In this R program, we give the number directly to the function convert_to_binary(). Check if the given decimal number is greater than 1 if yes divide the number successively by 2. The remainder is printed in reverse order.
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
convert_to_binary <- function(decnum) {
if(decnum > 1) {
convert_to_binary(as.integer(decnum/2))
}
cat(decnum %% 2)
}
convert_to_binary(52)
110100