Program for Sum of the digits of a given number

10 Jun, 2022
Given a number, find sum of its digits.
Examples : 
Input : n = 687
Output : 21

Input : n = 12
Output : 3
General Algorithm for sum of digits in a given number: 
Get the numberDeclare a variable to store the sum and set it to 0Repeat the next two steps till the number is not 0Get the rightmost digit of the number with help of the remainder ‘%’ operator by dividing it by 10 and add it to sum.Divide the number by 10 with help of ‘/’ operator to remove the rightmost digit.Print or return the sum
Get the number
Declare a variable to store the sum and set it to 0
Repeat the next two steps till the number is not 0
Get the rightmost digit of the number with help of the remainder ‘%’ operator by dividing it by 10 and add it to sum.
Divide the number by 10 with help of ‘/’ operator to remove the rightmost digit.
Print or return the sum
Below are the solutions to get sum of the digits. 1. Iterative:
C++
C
Java
Python3
C#
PHP
Javascript
// C program to compute sum of digits in// number.#include <iostream>using namespace std; /* Function to get sum of digits */class gfg {public:    int getSum(int n)    {        int sum = 0;        while (n != 0) {            sum = sum + n % 10;            n = n / 10;        }        return sum;    }}; // Driver codeint main(){    gfg g;    int n = 687;    cout << g.getSum(n);    return 0;}// This code is contributed by Soumik
// C program to compute sum of digits in// number.#include <stdio.h> /* Function to get sum of digits */int getSum(int n){    int sum = 0;    while (n != 0) {        sum = sum + n % 10;        n = n / 10;    }    return sum;} // Driver codeint main(){    int n = 687;    printf(" %d ", getSum(n));    return 0;}
// Java program to compute// sum of digits in number.import java.io.*; class GFG {     /* Function to get sum of digits */    static int getSum(int n)    {        int sum = 0;         while (n != 0) {            sum = sum + n % 10;            n = n / 10;        }         return sum;    }     // Driver code    public static void main(String[] args)    {        int n = 687;         System.out.println(getSum(n));    }} // This code is contributed by Gitanjali
# Python 3 program to# compute sum of digits in# number. # Function to get sum of digits  def getSum(n):     sum = 0    while (n != 0):         sum = sum + int(n % 10)        n = int(n/10)     return sum  # Driver coden = 687print(getSum(n))
// C# program to compute// sum of digits in number.using System; class GFG {    /* Function to get sum of digits */    static int getSum(int n)    {        int sum = 0;         while (n != 0) {            sum = sum + n % 10;            n = n / 10;        }         return sum;    }     // Driver code    public static void Main()    {        int n = 687;        Console.Write(getSum(n));    }} // This code is contributed by Sam007
<?php// PHP Code to compute sum// of digits in number. // Function to get// $sum of digitsfunction getsum($n){    $sum = 0;    while ($n != 0)    {        $sum = $sum + $n % 10;        $n = $n/10;    }    return $sum;} // Driver Code$n = 687;$res = getsum($n);echo("$res"); // This code is contributed by// Smitha Dinesh Semwal.?>
<script> // Javascript program to compute sum of digits in// number. /* Function to get sum of digits */function getSum(n){    var sum = 0;    while (n != 0) {        sum = sum + n % 10;        n = parseInt(n / 10);    }    return sum;} // Driver codevar n = 687;document.write(getSum(n)); </script>
Chapters
descriptions off, selected
captions settings, opens captions settings dialog
captions off, selected
English
This is a modal window.
Beginning of dialog window. Escape will cancel and close the window.
End of dialog window.
21
Time Complexity : O(logn)
Auxiliary Space: O(1)
How to compute in a single line? The below function has three lines instead of one line, but it calculates the sum in line. It can be made one-line function if we pass the pointer to sum. 
C++
C
Java
Python3
C#
PHP
Javascript
#include <iostream>using namespace std; /* Function to get sum of digits */class gfg {public:    int getSum(int n)    {        int sum;         /* Single line that calculates sum */        for (sum = 0; n > 0; sum += n % 10, n /= 10)            ;         return sum;    }}; // Driver codeint main(){    gfg g;    int n = 687;    cout << g.getSum(n);    return 0;}// This code is contributed by Soumik
#include <stdio.h> /* Function to get sum of digits */int getSum(int n){    int sum;     /* Single line that calculates sum */    for (sum = 0; n > 0; sum += n % 10, n /= 10)        ;     return sum;} // Driver codeint main(){    int n = 687;    printf(" %d ", getSum(n));    return 0;}
// Java program to compute// sum of digits in number.import java.io.*; class GFG {     /* Function to get sum of digits */    static int getSum(int n)    {        int sum;         /* Single line that calculates sum */        for (sum = 0; n > 0; sum += n % 10, n /= 10)            ;         return sum;    }     // Driver code    public static void main(String[] args)    {        int n = 687;         System.out.println(getSum(n));    }} // This code is contributed by Gitanjali
# Function to get sum of digits  def getSum(n):     sum = 0     # Single line that calculates sum    while(n > 0):        sum += int(n % 10)        n = int(n/10)     return sum  # Driver coden = 687print(getSum(n)) # This code is contributed by# Smitha Dinesh Semwal
// C# program to compute// sum of digits in number.using System; class GFG {    static int getSum(int n)    {        int sum;         /* Single line that calculates sum */        for (sum = 0; n > 0; sum += n % 10, n /= 10)            ;         return sum;    }     // Driver code    public static void Main()    {        int n = 687;        Console.Write(getSum(n));    }} // This code is contributed by Sam007
<?php// PHP Code for Sum the// digits of a given number // Function to get sum of digitsfunction getsum($n){     // Single line that calculates $sum    for ($sum = 0; $n > 0; $sum += $n % 10,                                  $n /= 10);    return $sum;} // Driver Code$n = 687;echo(getsum($n)); // This code is contributed by// Smitha Dinesh Semwal.?>
<script> // Javascript program to compute// sum of digits in number. // Function to get sum of digitsfunction getSum(n){    let sum;     // Single line that calculates sum    for(sum = 0; n > 0;        sum += n % 10,        n = parseInt(n / 10))        ;    return sum;} // Driver codelet n = 687; document.write(getSum(n)); // This code is contributed by subhammahato348 </script>
21
Time Complexity : O(logn)
Auxiliary Space: O(1)
2. Recursive Thanks to Ayesha for providing the below recursive solution. 
Algorithm :
1) Get the number
2) Get the remainder and pass the next remaining digits
3) Get the rightmost digit of the number with help of the remainder '%' operator by dividing it by 10 and add it to sum.
   Divide the number by 10 with help of '/' operator to remove the rightmost digit.
4) Check the base case with n = 0
5) Print or return the sum
C++
C
Java
Python3
C#
PHP
Javascript
// C++ program to compute// sum of digits in number.#include <iostream>using namespace std;class gfg {public:    int sumDigits(int no)    {        if(no == 0){          return 0 ;        }               return (no % 10) + sumDigits(no / 10) ;    }}; // Driver codeint main(void){    gfg g;    cout << g.sumDigits(687);    return 0;}
// C program to compute// sum of digits in number.#include <stdio.h> int sumDigits(int no){  if(no == 0){    return 0 ;  }   return (no % 10) + sumDigits(no / 10) ;} int main(){    printf("%d", sumDigits(687));    return 0;}
// Java program to compute// sum of digits in number.import java.io.*; class GFG {     /* Function to get sum of digits */    static int sumDigits(int no)    {        if(no == 0){          return 0 ;        }         return (no % 10) + sumDigits(no / 10) ;     }     // Driver code    public static void main(String[] args)    {        System.out.println(sumDigits(687));    }} // This code is contributed by Gitanjali
# Python program to compute# sum of digits in number.  def sumDigits(no):    return 0 if no == 0 else int(no % 10) + sumDigits(int(no/10))  # Driver codeprint(sumDigits(687)) # This code is contributed by# Smitha Dinesh Semwal
// C# program to compute// sum of digits in number.using System; class GFG {    /* Function to get sum of digits */    static int sumDigits(int no)    {        return no == 0 ? 0 : no % 10 + sumDigits(no / 10);    }     // Driver code    public static void Main()    {        Console.Write(sumDigits(687));    }} // This code is contributed by Sam007
<?php// PHP program to compute// sum of digits in number.function sumDigits($no){return $no == 0 ? 0 : $no % 10 +                      sumDigits($no / 10) ;} // Driver Codeecho sumDigits(687); // This code is contributed by aj_36?>
<script>// Program to compute// sum of digits in number  // Function to get sum of digits               function sumDigits(no)     {        if(no == 0){          return 0 ;        }         return (no % 10) + sumDigits(parseInt(no/10)) ;      }       // Driver code      document.write(sumDigits(687));       // This is code is contributed by simranarora5sos</script>
21
Time Complexity : O(logn)
Auxiliary Space: O(logn)
3.Taking input as String
When the number of digits of that number exceeds 1019 , we can’t take that number as an integer since the range of long long int doesn’t satisfy the given number. So take input as a string, run a loop from start to the length of the string and increase the sum with that character(in this case it is numeric)
Below is the implementation of the above approach
C++14
Java
Python3
C#
Javascript
// C++ implementation of the above approach#include <iostream>using namespace std;int getSum(string str){    int sum = 0;     // Traversing through the string    for (int i = 0; i < str.length(); i++) {        // Since ascii value of        // numbers starts from 48        // so we subtract it from sum        sum = sum + str[i] - 48;    }    return sum;} // Driver Codeint main(){    string st = "123456789123456789123422";    cout << getSum(st);    return 0;}
// Java implementation of the above approachimport java.io.*;class GFG {     static int getSum(String str)    {        int sum = 0;         // Traversing through the string        for (int i = 0; i < str.length(); i++) {             // Since ascii value of            // numbers starts from 48            // so we subtract it from sum            sum = sum + str.charAt(i) - 48;        }        return sum;    }     // Driver Code    public static void main(String[] args)    {        String st = "123456789123456789123422";        System.out.print(getSum(st));    }} // This code is contributed by Dharanendra L V.
# Python implementation of the above approachdef getSum(n):    # Initializing sum to 0    sum = 0    # Traversing through string    for i in n:        # Converting char to int        sum = sum + int(i)     return sum  n = "123456789123456789123422"print(getSum(n))
// C# implementation of the above approachusing System;public class GFG {    static int getSum(String str)    {        int sum = 0;         // Traversing through the string        for (int i = 0; i < str.Length; i++) {             // Since ascii value of            // numbers starts from 48            // so we subtract it from sum            sum = sum + str[i] - 48;        }        return sum;    }     // Driver Code    static public void Main()    {        String st = "123456789123456789123422";        Console.Write(getSum(st));    }} // This code is contributed by Dharanendra L V.
<script>// Javascript implementation of the above approach function getSum(str){    let sum = 0;     // Traversing through the string    for (let i = 0; i < str.length; i++)    {             // Since ascii value of        // numbers starts from 48        // so we subtract it from sum        sum = sum + parseInt(str[i]);    }    return sum;} // Driver Codelet st = "123456789123456789123422";document.write(getSum(st)); // This code is contributed by subhammahato348.</script>
104
Time Complexity : O(logn)
Auxiliary Space: O(1)
4. Using Tail Recursion 
This problem can also be solved using Tail Recursion. Here is an approach to solving it.
1. Add another variable “Val” to the function and initialize it to ( val = 0 )
2. On every call to the function add the mod value (n%10) to the variable as “(n%10)+val” which is the last digit in n. Along with pass the variable n as n/10. 
3. So on the First call it will have the last digit. As we are passing n/10 as n, It follows until n is reduced to a single digit. 
4. n<10 is the base case so When n < 10, then add the n to the variable as it is the last digit and return the val which will have the sum of digits
C++
Java
Python3
C#
Javascript
// C++ program for the above approach#include <iostream>using namespace std; // Function to check sum// of digit using tail recursionint sum_of_digit(int n, int val){    if (n < 10)    {        val = val + n;        return val;    }    return sum_of_digit(n / 10, (n % 10) + val);} // Driver codeint main(){    int num = 12345;    int result = sum_of_digit(num, 0);         cout << "Sum of digits is " << result;         return 0;} // This code is contributed by subhammahato348
// Java program for the above approachimport java.io.*;import java.lang.*;import java.util.*; class sum_of_digits {       // Function to check sum    // of digit using tail recursion    static int sum_of_digit(int n, int val)    {        if (n < 10) {            val = val + n;            return val;        }        return sum_of_digit(n / 10, (n % 10) + val);    }     // Driven Program to check above    public static void main(String args[])    {        int num = 12345;        int result = sum_of_digit(num, 0);        System.out.println("Sum of digits is " + result);    }}
# Python3 program for the above approach # Function to check sum# of digit using tail recursiondef sum_of_digit(n, val):         if (n < 10):        val = val + n        return val             return sum_of_digit(n // 10, (n % 10) + val) # Driver codenum = 12345result = sum_of_digit(num, 0) print("Sum of digits is", result) # This code is contributed by subhammahato348
// C# program for the above approachusing System; class GFG{ // Function to check sum// of digit using tail recursionstatic int sum_of_digit(int n, int val){    if (n < 10)    {        val = val + n;        return val;    }    return sum_of_digit(n / 10, (n % 10) + val);} // Driver codepublic static void Main(){    int num = 12345;    int result = sum_of_digit(num, 0);     Console.Write("Sum of digits is " + result);}} // This code is contributed by subhammahato348
<script> // Javascript program for the above approach // Function to check sum// of digit using tail recursionfunction sum_of_digit(n, val){    if (n < 10)    {        val = val + n;        return val;    }    return sum_of_digit(parseInt(n / 10),    (n % 10) + val);} // Driver code    let num = 12345;    let result = sum_of_digit(num, 0);         document.write("Sum of digits is " + result); // This code is contributed by subhammahato348 </script>
Sum of digits is 15
Time Complexity : O(logn)
Auxiliary Space: O(logn)
Please write comments if you find the above codes/algorithms incorrect, or find better ways to solve the same problem.
jit_t
SoumikMondal
RishabhPrabhu
vikkycirus
dharanendralv23
SatheeshKumarMR
gauravl3hardwaj
rutvik_56
subhammahato348
simranarora5sos
ruhelaa48
prasanna1995
susobhanakhuli
helderdacosta
cpp-puzzle
number-digits
C Language
C++
Recursion
Recursion
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
std::sort() in C++ STL
Bitwise Operators in C/C++
Arrays in C/C++
Substring in C++
Dynamic Memory Allocation in C using malloc(), calloc(), free() and realloc()
Vector in C++ STL
Map in C++ Standard Template Library (STL)
Initialize a vector in C++ (7 different ways)
std::sort() in C++ STL
Bitwise Operators in C/C++