C Program to Calculate Generic Root of a Number using Ternary Operator

Lets write a C program to calculate Generic Root of a Number using Ternary Operator or Conditional Operator.

Related Read:
C Program to Find Generic Root of a Number
Ternary Operator / Conditional Operator In C

For Example: If user input number is 65987, then we add all the individual digits of the number i.e., 6 + 5 + 9 + 8 + 7 = 35. We got 35. Now we add individual digits of number 35 i.e., 3 + 5 = 8. So Generic Root of number 65987 is 8.

Source Code: C Program to Calculate Generic Root of a Number using Ternary Operator

 
#include < stdio.h >

int main()
{
    int num, res;

    printf("Enter a number above 10\n");
    scanf("%d", &num);

    printf("Generic Root of %d is %d\n", num, (res = num % 9) ? res : 9 );

    return 0;
}

Output 1:
Enter a number above 10
65987
Generic Root of 65987 is 8

Output 2:
Enter a number above 10
8
Generic Root of 8 is 8

Output 3:
Enter a number above 10
456
Generic Root of 456 is 6

Output 4:
Enter a number above 10
78910
Generic Root of 78910 is 7

Output 5:
Enter a number above 10
5555
Generic Root of 5555 is 2

C Program to Calculate Generic Root of a Number using Ternary Operator



YouTube Link: https://www.youtube.com/watch?v=CpEOFsvQtGg [Watch the Video In Full Screen.]


Logic To Find Generic Root of a Number using Ternary Operator

(result = num % 9) ? result : 9;

OR

(num % 9) ? (num % 9) : 9;

We divide the user input number by 9 and store the remainder inside variable result. If the number is perfectly divisible by 9 or if the result is zero then we output 9 orelse we output the value present in variable result. Variable result will have the Generic Root of the user entered number. We are applying modular division on the user entered number. And we are dividing it by 9 because 9 is the biggest single digit number and by modulo division of number by 9 we get the Generic Root of the number.

For list of all c programming interviews / viva question and answers visit: C Programming Interview / Viva Q&A List

For full C programming language free video tutorial list visit:C Programming: Beginner To Advance To Expert