poorvankBhatia poorvankBhatia - 1 year ago 131
C Question

Generic root of a number in c

Generic root of a number is defined as the sum of digits of a number until we get a single digit.
For example:

Generic root of 456: 4 + 5 + 6 = 15 since 15 is two digit numbers so 1 + 5 = 6

So, generic root of 456 = 6

I solved this problem by recursively adding the digits of the number until a single digit number is obtained and the program worked fine. I searched the web and found a very small solution for it which i was unable to understand:

int main()
{ int n,x;
printf("Enter no");
printf("Generic root: %d",(x=n%9)?x:9);
return 0;

I am not able to understand how the ternary operator is working here!? How is it calculating the Generic root of a number

Answer Source

A number n modulus 9 returns either its root or 0, in which case the root is 9.

  1. Calculate n % 9 to get the root
  2. If the result is 0, then the root is 9

So (x=n%9)?x:9 means that if n mod 9 is zero, assign 9.

You can also achieve this without the ternary operator:

x = 1+((n-1)%9)

The modulus 9 trick is called the congruence formula.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download