Rust program to convert an integer number to binary using recursion

Rust | Integer to Binary Conversion: Given an integer number, we have to convert it into a binary number using recursion.
Submitted by Nidhi, on October 12, 2021

Problem Solution:

In this program, we will create a recursive function to convert an integer number into binary and return the result to the calling function.

Program/Source Code:

The source code to convert an integer number to binary using recursion is given below. The given program is compiled and executed successfully.

// Rust program to convert integer number 
// to binary using recursion

fn dec2bin(num:i32)->i32
{
    if num == 0
    {
        return 0;
    }
    else
    {
        return num % 2 + 10 * dec2bin(num / 2);
    }
}

fn main() {
    let num:i32=6;
    
    let res = dec2bin(num);
    
    println!("The binary equivalent is {}.",res);
}

Output:

The binary equivalent is 110.

Explanation:

In the above program, we created two functions dec2bin() and main(). The dec2bin() function is a recursive function, which is used to convert an integer number into binary and return the result to the calling function.

In the main() function, we called the dec2bin() function and printed the result.

Rust Functions Programs »





Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.