Sum of digits of a number until the sum is a single digit
Question:
Calculate the sum of the digits of a number until the number is a single digit.
Logic:
- Get the input number from the user.
- Then find the sum of all digits.
- Continue the addition process until sum value is a single digit.
- At last print the sum value.
Algorithm:
- Get the input element from the user.
- Add all digits of the number.
- Then check the sum values digit count is >1.
- Digit count value is found by using count function.
- Repeat step 2 to 4 until sum value is a single digit.
- Then print the sum value.
Program:
#include<stdio.h> void main() { int n,sum=0; clrscr(); printf("enter the number:"); scanf("%d",&n); while(n>0) { sum=sum+n%10; //add the digits n=n/10; //removes last digit if(n==0) { /*added value is assignes to n for processing addition of digits operation only when count of digit >1.*/ n=sum; sum=0; //intialize to zero for performing another addtion if(count(n)==1) //when count(n) is 1 exits from the loop { break; } } } printf("%d",n); //prints single digit sum value getch(); } int count(int x) //returns the count of digits { int i=0; while(x>0) { x=x/10; i++; } return i; }