Answers for "generate n-bit gray code in c"

C
4

generate n-bit gray code in c

#include <stdio.h>
#include <math.h>
int decimal_to_binary(int);
int main(void)
{
    int bits,gray;
    printf("What is the number of bits? ");
    scanf("%d",&bits);
    int max_num = pow(2,bits)-1;
    for(int j=0; j<=max_num; j++)
    {
        gray=j^(j>>1);
        printf("%d\n",decimal_to_binary(gray));
    }
    return 0;
}
int decimal_to_binary(int num)
{
    int binary=0,i=0;
    while(num!=0)
    {
        int reminder = num%2;
        binary += reminder*pow(10,i);
        num/=2;
        i++;
    }
    return binary;
}
Posted by: Guest on April-18-2022

Code answers related to "C"

Browse Popular Code Answers by Language