Rust program to convert binary to Gray code using recursion

Rust | Convert Binary to Gray Code: Given a binary number, we have to convert it into Gray code using recursion.
Submitted by Nidhi, on October 12, 2021

Problem Solution:

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

Program/Source Code:

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

```// Rust program to convert binary
// to Gray code using recursion

fn bin2gray(n:i32)->i32
{
if !(n>0)
{
return 0;
}
let a:i32 = n % 10;
let b:i32 = n / 10 % 10;

if (a>0 && !(b>0)) || (!(a>0) && (b>0))
{
return (1 + 10 * bin2gray(n / 10));
}

return (10 * bin2gray(n / 10));
}

fn main() {
let num:i32=11011011;

let res = bin2gray(num);

println!("The Gray codr is {}.",res);
}
```

Output:

```The Gray code is 10110110.
```

Explanation:

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

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