This blog is under construction

Sunday, 21 July 2013

C program to convert decimal to binary using recursion

Write a C program to convert decimal to binary using recursion.


  #include <stdio.h>
  #include <string.h>

  /* finds the reverse of the given input */
  void strrev(char *binary, char *output, int *len) {
        if (*len >= 0) {
                *output = *(binary + *len);
                *len = *len - 1;
                strrev(binary, output + 1, len);
        } else {
                *output = '\0';
        }
        return;
  }

  /*
   * converts decimal to binary.  But, the binary output
   * will be in reverse order.  We need to reverse the binary
   * output to get the exact binary value.
   */
  void decimalToBinary(int num, char *binary) {
        if (num) {
                *binary = (num % 2) + '0';
                decimalToBinary(num / 2, binary + 1);
        } else {
                *binary = '\0';
        }
        return;
  }

  int main() {
        int num, len;
        char binary[256], output[256];

        /* get the input decimal value from the user */
        printf("Enter your input value:");
        scanf("%d", &num);

        if (!num) {
                printf("Binary Value: 0\n");
                return 0;
        }

        /* decimal to binary conversion */
        decimalToBinary(num, binary);
        len = strlen(binary) - 1;
        strrev(binary, output, &len);

        /* print the result */
        printf("Binary Value: %s\n", output);
        return 0;
  }



  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  Enter your input value:65535
  Binary Value: 1111111111111111


No comments:

Post a Comment