The Wayback Machine - https://web.archive.org/web/20210127181625/https://www.geeksforgeeks.org/program-for-sum-of-the-digits-of-a-given-number/
Related Articles

Related Articles

Program for Sum of the digits of a given number
  • Difficulty Level : Easy
  • Last Updated : 20 Jan, 2021

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: 

  1. Get the number
  2. Declare a variable to store the sum and set it to 0
  3. Repeat the next two steps till the number is not 0
  4. Get the rightmost digit of the number with help of remainder ‘%’ operator by dividing it with 10 and add it to sum.
  5. Divide the number by 10 with help of ‘/’ operator
  6. Print or return the sum

Below are the solutions to get sum of the digits. 
1. Iterative:

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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 code
int main()
{
    gfg g;
    int n = 687;
    cout << g.getSum(n);
    return 0;
}
// This code is contributed by Soumik

chevron_right


C

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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 code
int main()
{
    int n = 687;
    printf(" %d ", getSum(n));
    return 0;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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 code
n = 687
print(getSum(n))

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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

chevron_right


PHP

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
// PHP Code to compute sum
// of digits in number.
 
// Function to get
// $sum of digits
function 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.
?>

chevron_right


Output



21

How to compute in a single line? 
Below function has three lines instead of one line but it calculates sum in line. It can be made one line function if we pass pointer to sum. 

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

#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 code
int main()
{
    gfg g;
    int n = 687;
    cout << g.getSum(n);
    return 0;
}
// This code is contributed by Soumik

chevron_right


C

filter_none

edit
close

play_arrow

link
brightness_4
code

#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 code
int main()
{
    int n = 687;
    printf(" %d ", getSum(n));
    return 0;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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 code
n = 687
print(getSum(n))
 
# This code is contributed by
# Smitha Dinesh Semwal

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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

chevron_right


PHP

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
// PHP Code for Sum the
// digits of a given number
 
// Function to get sum of digits
function 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.
?>

chevron_right


Output

21

2. Recursive 
Thanks to ayesha for providing the below recursive solution. 

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program to compute
// sum of digits in number.
#include <iostream>
using namespace std;
class gfg {
public:
    int sumDigits(int no)
    {
        return no == 0 ? 0 : no % 10 + sumDigits(no / 10);
    }
};
 
// Driver code
int main(void)
{
    gfg g;
    cout << g.sumDigits(687);
    return 0;
}

chevron_right


C

filter_none

edit
close

play_arrow

link
brightness_4
code

// C program to compute
// sum of digits in number.
#include <stdio.h>
using namespace std;
int sumDigits(int no)
{
    return no == 0 ? 0 : no % 10 + sumDigits(no / 10);
}
 
int main(void)
{
    printf("%d", sumDigits(687));
    return 0;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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)
    {
        return no == 0 ? 0 : no % 10 + sumDigits(no / 10);
    }
 
    // Driver code
    public static void main(String[] args)
    {
        System.out.println(sumDigits(687));
    }
}
 
// This code is contributed by Gitanjali

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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 code
print(sumDigits(687))
 
# This code is contributed by
# Smitha Dinesh Semwal

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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

chevron_right


PHP

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
// PHP program to compute
// sum of digits in number.
function sumDigits($no)
{
return $no == 0 ? 0 : $no % 10 +
                      sumDigits($no / 10) ;
}
 
// Driver Code
echo sumDigits(687);
 
// This code is contributed by aj_36
?>

chevron_right


Output

21

3.Taking input as String

When the number of digits of that number exceeds 1019 , we can’t take that number as 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

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ implementation of the above aprroach
#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 Code
int main()
{
    string st = "123456789123456789123422";
    cout << getSum(st);
    return 0;
}

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python implementation of the above aprroach
def 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))

chevron_right


Output

104

Please write comments if you find the above codes/algorithms incorrect, or find better ways to solve the same problem.
 

Attention reader! Don’t stop learning now. Get hold of all the important C++ Foundation and STL concepts with the C++ Foundation and STL courses at a student-friendly price and become industry ready.




My Personal Notes arrow_drop_up
Recommended Articles
Page :