# C Program to Convert Binary to Gray Code using Recursion

«
»

This is a C program to convert binary code of a number into its equivalent gray’s code using recursion.

Problem Description

This C program using recursion evaluates the gray code equivalent of a binary number.

Problem Solution

A gray is also represented using 0s and 1s. The speciality of gray code is that only one bit is changed in 2 consecutive numbers, say 3 and 4.

Program/Source Code

Here is the source code of the C program to display a linked list in reverse. The C program is successfully compiled and run on a Linux system. The program output is also shown below.

```/*
* C Program to Convert Binary Code of a Number into its Equivalent
* Gray's Code using Recursion
*/
#include <stdio.h>

int bintogray(int);

int main ()
{
int bin, gray;

printf("Enter a binary number: ");
scanf("%d", &bin);
gray = bintogray(bin);
printf("The gray code of %d is %d\n", bin, gray);
return 0;
}

int bintogray(int bin)
{
int a, b, result = 0, i = 0;

if (!bin)
{
return 0;
}
else
{
a = bin % 10;
bin = bin / 10;
b = bin % 10;
if ((a && !b) || (!a && b))
{
return (1 + 10 * bintogray(bin));
}
else
{
return (10 * bintogray(bin));
}
}
}```
Program Explanation

In this C program, we are reading a binary number using ‘bin’ variable, A gray is also represented using 0s and 1s. The specialty of gray code is that only one bit is changed in 2 consecutive numbers, say 3 and 4.

Sanfoundry Certification Contest of the Month is Live. 100+ Subjects. Participate Now!

The bintogra() function is used to evaluate the gray code equivalent of a binary number. While loop is used to check the value of ‘bin’ variable is not equal to 0. If the condition is true execute the loop. Compute the modulus of the value of ‘bin’ variable by 10 and assign to ‘a’ variable. Divide the value of ‘num’ variable by 10 and assign the value to ‘bin’ variable. Compute the modulus of the value of ‘bin’ variable by 10 and assign the value to ‘b’ variable.

If condition statement is used to check the value of ‘a’ variable and the negation of the value of ‘b’ variable is true and the negation of the value of ‘a’ variable and the value of ‘b’ variable is true by using the logical OR operator.

If the condition is true execute the statement. Multiply the resulted value with 10 integer value. Otherwise, if the condition is false execute the else statement by calling the bintogray() method passing ‘bin’ variable value as argument. Multiply the resulted value with 10 integer value and return the result to the called function ‘gray’ variable. Print the binary code of a number into its equivalent gray code using recursion.

Runtime Test Cases
```
\$ cc pgm21.c
\$ a.out
Enter a binary number:  1011101
The gray code of 1011101 is 1110011```

Sanfoundry Global Education & Learning Series – 1000 C Programs.

Here’s the list of Best Books in C Programming, Data-Structures and Algorithms 