- Asked 2/16
- 2068 Chaitra · 6 marks
- 2071 Shrawan · 4 marks
Sum of digits until single digit
Short answer
Repeatedly replace the number by the sum of its digits (using n % 10 and n /= 10) until it becomes a single digit. For 12345, the intermediate sum is 15, then the final single digit is 6.
Write a program in C that calculates the sum of digits entered by the user successively until the sum reduces to a single digit number. For example, 12345 => 1+2+3+4+5=15=>1+5=6. (Find out sum of digit of number until the number becomes one digit number [891>18>9].)
Logic: repeatedly extract each digit with n % 10, add it, and remove it with n / 10. Take the sum as the new number and repeat until the number is below 10 (a single digit).
#include <stdio.h>
int main(void)
{
long n;
int sum;
printf("Enter a number: ");
scanf("%ld", &n);
while (n > 9)
{
sum = 0;
while (n > 0)
{
sum += n % 10;
n /= 10;
}
printf("Sum of digits = %d\n", sum);
n = sum;
}
printf("Single digit = %ld\n", n);
return 0;
}
Output for 12345:
Enter a number: Sum of digits = 15
Sum of digits = 6
Single digit = 6
Output for 891:
Enter a number: Sum of digits = 18
Sum of digits = 9
Single digit = 9
Explanation
- The inner
while (n > 0)loop adds the digits: 1+2+3+4+5 = 15. - The outer loop
while (n > 9)repeats with n = 15: 1+5 = 6, and 6 is a single digit, so it stops.
✓ Answer checked by Claude Opus 5.5 (high effort)
Related questions
- Sum and average until 0 is entered · Computer Programming, chapter 5
- Sum of digits using recursion · Computer Programming, chapter 6
- Complex number sum via functions · Computer Programming, chapter 8
- GOTO types; sum of series program · Computer Programming, chapter 11
- Count even and odd until -1 · Computer Programming, chapter 5
- Count prime and composite until -1 · Computer Programming, chapter 5
- Sum of digits processor · Embedded System, chapter 2
- C program: sum of two 8-bit BCD numbers · Embedded System, chapter 9
- Poker test, 1000 four-digit numbers (2069) · Simulation and Modeling, chapter 6 · asked 3×
- Prime number program: procedural and OOP · Object Oriented Programming, chapter 1