This blog is under construction

Sunday, 21 July 2013

C program to extract digits of a number using recursion

Write a C program to extract digits of a number using recursion.


  #include <stdio.h>

  /* extract digits of the given numer */
  void extractDigits(int num, int *count, int *digits) {
        if (num) {
                digits[*count] = num % 10;
                *count = *count + 1;

                /* recursive call */
                extractDigits(num / 10, count, digits);
        }
        return;
  }

  int main() {
        int i, num, count = 0, digits[32];

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

        /* if the user input is 0 */
        if (!num) {
                printf("Digit 1 is 0\n");
                return 0;
        }

        /* extracts digits of the given number */
        extractDigits(num, &count, digits);

        /* print the digits of the given number */
        for (i = count - 1; i >= 0; i--) {
                printf("Digit %d is %d\n", (count - i), digits[i]);
        }

        return 0;
  }



  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  Enter your input value:123456
  Digit 1 is 1
  Digit 2 is 2
  Digit 3 is 3
  Digit 4 is 4
  Digit 5 is 5
  Digit 6 is 6


No comments:

Post a Comment