C Program to Convert Binary Code of a Number into its Equivalent Gray’s Code using Recursion


This C program using recursion, evaluates the gray code equivalent of a binary number. 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.
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.
  1. /*
  2.  * C Program to Convert Binary Code of a Number into its Equivalent 
  3.  * Gray's Code using Recursion
  4.  */
  5. #include <stdio.h>
  6.  
  7. int bintogray(int);
  8.  
  9. int main ()
  10. {
  11.     int bin, gray;
  12.  
  13.     printf("Enter a binary number: ");
  14.     scanf("%d", &bin);
  15.     gray = bintogray(bin);
  16.     printf("The gray code of %d is %d\n", bin, gray);
  17.     return 0;
  18. }
  19.  
  20. int bintogray(int bin)
  21. {
  22.     int a, b, result = 0, i = 0;
  23.  
  24.     if (!bin)
  25.     {
  26.         return 0;
  27.     }
  28.     else
  29.     {
  30.         a = bin % 10;
  31.         bin = bin / 10;
  32.         b = bin % 10;
  33.         if ((a && !b) || (!a && b))
  34.         {
  35.             return (1 + 10 * bintogray(bin));
  36.         }
  37.         else
  38.         {
  39.             return (10 * bintogray(bin));
  40.         }
  41.     }
  42. }

$ cc pgm21.c
$ a.out
Enter a binary number:  1011101
The gray code of 1011101 is 1110011

0 comments:

Post a Comment

 
Top