Sum of digits of a number until the sum is a single digit

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:

  1. Get the input element from the user.
  2. Add all digits of the number.
  3. Then check the sum values digit count is >1.
  4. Digit count value is found by using count function.
  5. Repeat step 2 to 4 until sum value is a single digit.
  6. 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;
}

You might also like:

To Count The Digits In A Number Using Recursion

Follow For Instant Updates

Join WhatsApp Group: link
Join our Telegram Channel: link
Like our Facebook Page:  link
Subscribe to our Youtube channel: link

Vignesh

A Computer Science graduate who likes to make things simpler. When he’s not working, you can find him surfing the web, learning facts, tricks and life hacks. He also enjoys movies in his leisure time.
0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x