C Program for Sum of digits of a given number (3 ways)

By | August 25, 2020

C Program for Sum of digits of a given number.

Examples :

Input : 123
Output : 6

Input : 1995
Output : 24 

Algorithm :
To get sum of each digits by c program, use the following algorithm:

  1. Get number by user
  2. Get the modulus/remainder of the number
  3. Sum the remainder of the number
  4. Divide the number by 10
  5. Repeat the step 2 while number is greater than 0.

Implementation :

1. Iterative method

// C program for Sum of digits of a given number
# include<stdio.h> 
  
int main() 
{ 
    // take input
  int n = 123; 
  
  // take a variable to store sum of digits
  int sum =0 ; 
  
  // iterative
  while (n != 0) 
   { 
       // store sumne of digit from LSB
       sum = sum + n % 10; 
       
       // remove last LSB
       n = n/10; 
   } 
  
  // print sum of digits
  printf(" %d ", sum); 
  
  // successful completion
  return 0; 
} 

Output :

6 

2. Sum in single line

// C program for Sum of digits of a given number
# include<stdio.h> 
  
int main() 
{ 
    // take input
  int n = 123; 
  
  // take a variable to store sum of digits
  int sum ;
  
  for (sum = 0; n > 0; sum += n % 10, n /= 10); 
  
  // print sum of digits
  printf(" %d ", sum); 
  
  // successful completion
  return 0; 
} 

Output :

6 

3. Recursive method

// C program for Sum of digits of a given number
# include<stdio.h> 

// getSum function to sum of digits
int getSum(int n) 
{  
   
  // take a variable to store sum of digits   
   int sum = 0; 
  
  while (n != 0) 
   { 
       // store sumne of digit from LSB
       sum = sum + n % 10; 
       
       // remove last LSB
       n = n/10; 
   } 
   
   // returned sum of digits
   return sum; 
}   
  
// driver code  
int main() 
{ 
    // take input
  int n = 123; 
  
  // call getSum function 
  // prints its returned value
  printf(" %d ", getSum(n)); 
  
  // successful completion
  return 0; 
} 

Output :

6 

Please write comments if you find anything incorrect. A gentle request to share this topic on your social media profile.