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.
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.
Output:
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.
need an explanation for this answer? contact us directly to get an explanation for this answer