Written by Sai Sameera Thota on February 24, 2013 in C > Programming

C Program to perform Sum of Digits until Single Digit is obtained

GET ALERTS:

Get our Latest updates delivered to your mailbox!

This Program is used to Find the sum of the digits of a number repeatedly until we get a single digit output. For example if we take a number : 1234, it will be calculated as 1+2+3+4 = 10 then 1+0 = 1. So the final Result will be 1.

First we are requesting the user an input. Then we are storing it in the variable n. Then we are diving the given number by 9 and using the modulus operator to get the remainder. Then if given number is 0, we are printing that the Single Digit is 0 else we are checking the number in the rem variable. If it is 0 then the resulting single digit will be 9 else we will print the value present in rem variable.

C Program to perform Sum of Digits until Single Digit is obtained

#include<stdio.h>
#include<conio.h>
void main()
{
      int n,rem;
      printf("\nEnter a number : ");
      scanf("%d",&n);
      rem = n%9;
      if(n==0)
      {
              printf("\nSingle digit result is 0");
      }
      else
      {
              if(rem==0)
                        printf("\nSingle digit result is 9");
              else
                        printf("\nSingle digit result is %d",rem);
      }
      getch();
}

The above program can also be written as the following:

#include<stdio.h>
#include<conio.h>
void main()
{
      int n,rem,sum = 0;
      printf("\nEnter a number : ");
      scanf("%d",&n);
      while(n > 0)
      {
                 while(n != 0)
                 {
                      rem = n%10;
                      sum = sum+rem;
                      n=n/10;
                 }
                 if(sum > 9)
                 {
                        n = sum;
                        sum = 0;
                 }
                 
      }
      printf("%d",sum);
      getch();
}

Output:

single_digit

{ 0 comments… add one now }

Leave a Comment

Previous post:

Next post: