This blog is under construction

Tuesday 9 July 2013

C program to calculate generic root of any number

What is Generic root of a number?
Find the sum of digits of the number until we get a single digit output.  And the resultant number is called generic number.

Example: 456791
4 + 5 + 6 + 7 + 9 + 1 = 32
3 + 2 = 5

So, 5 is the generic root of 456791.

Write a C program to calculate generic root of the given number.


  #include <stdio.h>

  /* returns the sum of digits of the given number */
  int genericRoot(int num) {
        int res = 0;
        while (num > 0) {
                res = res + (num % 10);
                num = num / 10;
        }
        return res;
  }

  int main() {
        int num;

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

        /* find the generic root of the given input */
        while (num > 10) {
                num = genericRoot(num);
        }

        /* print the result */
        printf("Generic Root is %d\n", num);
        return 0;
  }



  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  Enter your input value:456791
  Generic Root is 5






See Also:

1 comment: