Sum of digits C program to calculate the sum of digits of a number, we use modulus operator (%) to extract individual digits of a number and keep on adding them.
Sum of digits of a number in C
#include <stdio.h>
int main()
{
int n, t, sum = 0, remainder;
printf("Enter an integer\n");
scanf("%d", &n);
t = n;
while (t != 0)
{
remainder = t % 10;
sum = sum + remainder;
t = t / 10;
}
printf("Sum of digits of %d = %d\n", n, sum);
return 0;
}
If you wish, you can modify the input variable (n) and without using an additional variable (t), but we don't recommend it.
Output of program:
For example, if the input is 98, the variable sum is 0 initially98%10 = 8 (% is modulus operator, which gives us the remainder when 98 is divided by 10).sum = sum + remainderso sum = 8 now.98/10 = 9 because in C language, whenever we divide an integer by another one, we get an integer.9%10 = 9sum = 8 (previous value) + 9sum = 179/10 = 0.
So finally, n = 0, the loop ends; we get the required sum.
Download Add digits program.
C program to find sum of digits using for loop
#include <stdio.h>
int main()
{
int n, sum = 0, r;
printf("Enter a number\n");
for (scanf("%d", &n); n != 0; n = n/10) {
r = n % 10;
sum = sum + r;
}
printf("Sum of digits of a number = %d\n", sum);
return 0;
}
Calculate sum of digits in C without modulus operator
C program to find the sum of digit(s) of an integer that does not use modulus operator. Our program uses a character array (string) for storing an integer. We convert its every character into an integer and add all these integers.
#include <stdio.h>
int main()
{
int c, sum, t;
char n[1000];
printf("Input an integer\n");
scanf("%s", n);
sum = c = 0;
while (n[c] != '\0') {
t = n[c] - '0'; // Converting character to integer
sum = sum + t;
c++;
}
printf("Sum of digits of %s = %d\n", n, sum);
return 0;
}
An advantage of this method is that the input integer can be huge, which we can't store in an int or a long long data type variable. See the example below.
Output of program:
Input an integer
9876543210
Sum of digits of 9876543210 = 45
C program to find sum of digits of a number using recursion
#include <stdio.h>
int add_digits(int);
int main()
{
int n, result;
scanf("%d", &n);
result = add_digits(n);
printf("%d\n", result);
return 0;
}
int add_digits(int n) {
if (n == 0) // Base case
return 0;
return (n%10 + add_digits(n/10));
}
Improve Article
Save Article
Like Article
Improve Article
Save Article
Given a number, find the sum of its digits.
Examples :
Input: n = 687
Output: 21Input: n = 12
Output: 3
Follow the below steps to solve the problem:
- 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 adding it to the sum.
- Divide the number by 10 with help of ‘/’ operator to remove the rightmost digit.
- Print or return the sum
Below is the implementation of the above approach:
#include <bits/stdc++.h> using namespace std; class gfg { public: int getSum(int n) { int sum = 0; while (n != 0) { sum = sum + n % 10; n = n / 10; } return sum; } }; int main() { gfg g; int n = 687; cout << g.getSum(n); return 0; } |
#include <stdio.h> int getSum(int n) { int sum = 0; while (n != 0) { sum = sum + n % 10; n = n / 10; } return sum; } int main() { int n = 687; printf(" %d ", getSum(n)); return 0; } |
import java.io.*; class GFG { static int getSum(int n) { int sum = 0; while (n != 0) { sum = sum + n % 10; n = n / 10; } return sum; } public static void main(String[] args) { int n = 687; System.out.println(getSum(n)); } } |
def getSum(n): sum = 0 while (n != 0): sum = sum + int(n % 10) n = int(n/10) return sum if __name__ == "__main__": n = 687 print(getSum(n)) |
using System; class GFG { static int getSum(int n) { int sum = 0; while (n != 0) { sum = sum + n % 10; n = n / 10; } return sum; } public static void Main() { int n = 687; Console.Write(getSum(n)); } } |
<?php function getsum($n) { $sum = 0; while ($n != 0) { $sum = $sum + $n % 10; $n = $n/10; } return $sum; } $n = 687; $res = getsum($n); echo("$res"); ?> |
<script> function getSum(n) { var sum = 0; while (n != 0) { sum = sum + n % 10; n = parseInt(n / 10); } return sum; } var n = 687; document.write(getSum(n)); </script> |
Time Complexity: O(log N)
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 one line using for loop. It can be made one-line function if we pass the pointer to the sum.
Below is the implementation of the above approach:
#include <bits/stdc++.h> using namespace std; class gfg { public: int getSum(int n) { int sum; for (sum = 0; n > 0; sum += n % 10, n /= 10) ; return sum; } }; int main() { gfg g; int n = 687; cout << g.getSum(n); return 0; } |
#include <stdio.h> int getSum(int n) { int sum; for (sum = 0; n > 0; sum += n % 10, n /= 10) ; return sum; } int main() { int n = 687; printf(" %d ", getSum(n)); return 0; } |
import java.io.*; class GFG { static int getSum(int n) { int sum; for (sum = 0; n > 0; sum += n % 10, n /= 10) ; return sum; } public static void main(String[] args) { int n = 687; System.out.println(getSum(n)); } } |
def getSum(n): sum = 0 while(n > 0): sum += int(n % 10) n = int(n/10) return sum if __name__ == "__main__": n = 687 print(getSum(n)) |
using System; class GFG { static int getSum(int n) { int sum; for (sum = 0; n > 0; sum += n % 10, n /= 10) ; return sum; } public static void Main() { int n = 687; Console.Write(getSum(n)); } } |
<?php function getsum($n) { for ($sum = 0; $n > 0; $sum += $n % 10, $n /= 10); return $sum; } $n = 687; echo(getsum($n)); ?> |
<script> function getSum(n) { let sum; for(sum = 0; n > 0; sum += n % 10, n = parseInt(n / 10)) ; return sum; } let n = 687; document.write(getSum(n)); </script> |
Time Complexity: O(log N)
Auxiliary Space: O(1)
Sum of the digits of a given number using recursion:
Follow the below steps to solve the problem:
- Get the number
- Get the remainder and pass the next remaining digits
- Get the rightmost digit of the number with help of the remainder ‘%’ operator by dividing it by 10 and adding it to the sum.
- Divide the number by 10 with help of the ‘/’ operator to remove the rightmost digit.
- Check the base case with n = 0
- Print or return the sum
Below is the implementation of the above approach:
#include <iostream> using namespace std; class gfg { public: int sumDigits(int no) { if (no == 0) { return 0; } return (no % 10) + sumDigits(no / 10); } }; int main(void) { gfg g; cout << g.sumDigits(687); return 0; } |
#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; } |
import java.io.*; class GFG { static int sumDigits(int no) { if (no == 0) { return 0; } return (no % 10) + sumDigits(no / 10); } public static void main(String[] args) { System.out.println(sumDigits(687)); } } |
def sumDigits(no): return 0 if no == 0 else int(no % 10) + sumDigits(int(no/10)) if __name__ == "__main__": print(sumDigits(687)) |
using System; class GFG { static int sumDigits(int no) { return no == 0 ? 0 : no % 10 + sumDigits(no / 10); } public static void Main() { Console.Write(sumDigits(687)); } } |
<?php function sumDigits($no) { return $no == 0 ? 0 : $no % 10 + sumDigits($no / 10) ; } echo sumDigits(687); ?> |
<script> function sumDigits(no) { if(no == 0){ return 0 ; } return (no % 10) + sumDigits(parseInt(no/10)) ; } document.write(sumDigits(687)); </script> |
Time Complexity: O(log N)
Auxiliary Space: O(log N)
Sum of the digits of a given number with 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)
Follow the below steps to solve the problem:
- Declare a variable sum equal to zero
- Run a loop from zero to the length of the input string
- Add the value of each character into the sum, by converting the character into it’s integer value
- Return sum
Below is the implementation of the above approach:
#include <bits/stdc++.h> using namespace std; int getSum(string str) { int sum = 0; for (int i = 0; i < str.length(); i++) { sum = sum + str[i] - 48; } return sum; } int main() { string st = "123456789123456789123422"; cout << getSum(st); return 0; } |
import java.io.*; class GFG { static int getSum(String str) { int sum = 0; for (int i = 0; i < str.length(); i++) { sum = sum + str.charAt(i) - 48; } return sum; } public static void main(String[] args) { String st = "123456789123456789123422"; System.out.print(getSum(st)); } } |
def getSum(n): sum = 0 for i in n: sum = sum + int(i) return sum if __name__ == "__main__": n = "123456789123456789123422" print(getSum(n)) |
using System; public class GFG { static int getSum(String str) { int sum = 0; for (int i = 0; i < str.Length; i++) { sum = sum + str[i] - 48; } return sum; } static public void Main() { String st = "123456789123456789123422"; Console.Write(getSum(st)); } } |
<?php function getsum($str) { $sum = 0; for ($i = 0; $i<strlen($str); $i++) { $sum = $sum + (int)$str[$i]; } return $sum; } $str = "123456789123456789123422"; echo(getsum($str)); ?> |
<script> function getSum(str) { let sum = 0; for (let i = 0; i < str.length; i++) { sum = sum + parseInt(str[i]); } return sum; } let st = "123456789123456789123422"; document.write(getSum(st)); </script> |
Time Complexity: O(log N)
Auxiliary Space: O(1)
Sum of the digits of a given number using tail recursion:
Follow the below steps to solve the problem:
- Add another variable “Val” to the function and initialize it to ( Val = 0 )
- 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 passing the variable n as n/10.
- 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.
- 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
Below is the implementation of the above approach:
#include <bits/stdc++.h> using namespace std; 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); } int main() { int num = 12345; int result = sum_of_digit(num, 0); cout << "Sum of digits is " << result; return 0; } |
#include <stdio.h> 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); } int main() { int num = 12345; int result = sum_of_digit(num, 0); printf("Sum of digits is %d", result); return 0; } |
import java.io.*; import java.lang.*; import java.util.*; class sum_of_digits { 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); } public static void main(String args[]) { int num = 12345; int result = sum_of_digit(num, 0); System.out.println("Sum of digits is " + result); } } |
def sum_of_digit(n, val): if (n < 10): val = val + n return val return sum_of_digit(n // 10, (n % 10) + val) if __name__ == "__main__": num = 12345 result = sum_of_digit(num, 0) print("Sum of digits is", result) |
using System; class GFG { 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); } public static void Main() { int num = 12345; int result = sum_of_digit(num, 0); Console.Write("Sum of digits is " + result); } } |
<script> function sum_of_digit(n, val) { if (n < 10) { val = val + n; return val; } return sum_of_digit(parseInt(n / 10), (n % 10) + val); } let num = 12345; let result = sum_of_digit(num, 0); document.write("Sum of digits is " + result); </script> |
OutputSum of digits is 15
Time Complexity: O(log N)
Auxiliary Space: O(log N)
Please write comments if you find the above codes/algorithms incorrect, or find better ways to solve the same problem.