C program to convert a Binary number to Gray Code using Recursion

Here, we are going to learn how to convert a Binary number to Gray Code using Recursion in C programming language?
Submitted by Nidhi, on July 09, 2021

Problem Solution:

Here, we will read a number in binary format (1's and 0's) from the user and then convert it into corresponding Gray code using recursive function.

Program:

The source code to convert a binary number to Gray code using recursion is given below. The given program is compiled and executed using GCC compile on UBUNTU 18.04 OS successfully.

// C program to convert a Binary number to Gray Code
//  using recursion

#include <stdio.h>

unsigned long long int BinaryToGary(unsigned long long int binNum)
{
    int a = 0;
    unsigned long long int b = 0;
    int i = 0;

    if (binNum != 0) {
        a = binNum % 10;
        binNum = binNum / 10;
        b = binNum % 10;

        if ((a && !b) || (!a && b)) {
            return (1 + 10 * BinaryToGary(binNum));
        }
        else {
            return (10 * BinaryToGary(binNum));
        }
    }
    else {
        return 0;
    }
}

int main()
{
    unsigned long long int binNum = 0;
    unsigned long long int grayCode = 0;

    printf("Enter a binary number: ");
    scanf("%llu", &binNum);

    grayCode = BinaryToGary(binNum);

    printf("Gray code: %llu", grayCode);
    return 0;
}

Output:

RUN 1:
Enter a binary number: 111111111100
The gray code: 100000000010

RUN 2:
Enter a binary number: 1100110011
The gray code: 1010101010

RUN 3:
Enter a binary number: 1111
The gray code: 1000

RUN 4:
Enter a binary number: 1010
The gray code: 1111

Explanation:

In the above program, we created two functions BinaryToGary() and main() function. The BinaryToGary() function is a recursive function, which is used to convert the binary number to the corresponding gray code.

In the main() function, we read a number in binary format (1's and 0's) from the user and convert the input number to gray code using BinaryToGary() function and printed the result on the console screen.

C Number System Conversion Programs »





Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.