program to find sum of digits of a number reducing into single digit code example
Example 1: Write a function digitsum that calculates the digit sum of an integer. The digit sum of an integer is the sum of all its digits.
function digSum(n) {
let sum = 0;
let str = n.toString();
console.log(parseInt(str.substring(0, 1)));
for (let i = 0; i < str.length; i++) {
sum += parseInt(str.substring(i,i+1));
}
return sum;
}
Example 2: sum the digits of an integer
#include <stdio.h>
int getSum(unsigned long long n) {
int sum = 0;
for (; n; n /= 10)
sum += n % 10;
return sum;
}
int main(){
printf("Sum of digits = %d\n", getSum(555));
}