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

This C program, using iteration, 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.

/* * C Program to Convert Binary Code of a Number into its Equivalent * Gray's Code without using Recursion */ #include <stdio.h> #include <math.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; while (bin != 0) { a = bin % 10; bin = bin / 10; b = bin % 10; if ((a && !b) || (!a && b)) { result = result + pow(10, i); } i++; } return result; }

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.

The bintogray() function is used to evaluate the gray code equivalent of a binary number by passing the value of ‘bin’ variable as argument. 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.

Divide the value of ‘num’ variable by 10. Compute the modulus of the value of ‘bin’ variable value by 10.

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

If the condition is true execute the statement compute the value of 10 to the power of the value of ‘i’ variable and assign the value to ‘result’ variable. Print the binary code of a number into its equivalent gray’s code using printf statement.

$ cc pgm26.c -lm $ a.out Enter a binary number: 1111001010 The gray code of 1111001010 is 1000101111

**Sanfoundry Global Education & Learning Series – 1000 C Programs.**

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

**If you find any mistake above, kindly email to [email protected]**

**Related Posts:**

- Watch Advanced C Programming Videos
- Check C Books
- Practice BCA MCQs
- Apply for C Internship
- Check Computer Science Books