w3resource

C Exercises: Add repeatedly all digits of a given non-negative number until the result has only one digit


12. Add Digits to One Digit Variants

Write a C program to add repeatedly all digits of a given non-negative number until the result has only one digit.

Example:
Input: 48
Output: 2
Explanation: The formula is like: 4 + 8 = 12, 1 + 2 = 3.

Visual Presentation:

C Exercises: Add repeatedly all digits of a given non-negative number until the result has only one digit

Sample Solution:

C Code:

#include <stdio.h>

// Function to calculate the digital root of a number (single-digit sum)
static int addDigits(int num) {
    // Formula to calculate the digital root of a number using a mathematical property
    // The digital root of a positive integer num is equivalent to num - (num - 1) / 9 * 9
    return num - (num - 1) / 9 * 9;
}

// Main function to test the addDigits function with different numbers
int main(void) {
    int n = 12;
    printf("\nInitial number is %d, Single digit number is %d.", n, addDigits(n));
    n = 47;
    printf("\n\nInitial number is %d, Single digit number is %d.", n, addDigits(n));
    return 0;
}

Sample Output:

Initial number is 12, Single digit number is 3.

Initial number is 47, Single digit number is 2.

Flowchart:

Flowchart: Add repeatedly all digits of a given non-negative number until the result has only one digit

For more Practice: Solve these Related Problems:

  • Write a C program to repeatedly add digits of a number until a single-digit result is obtained using recursion.
  • Write a C program to compute the digital root of a number in a single expression without loops.
  • Write a C program to perform digit addition iteratively and print each intermediate sum.
  • Write a C program to optimize the digit sum process using mathematical properties to compute the digital root.

Go to:


PREV : Count Digit 1 Occurrences Variants.
NEXT : Power of Three Check Variants.

C Programming Code Editor:



Improve this sample solution and post your code through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.