Menu Close

Return the sum of digits in a number

Aaron is an engineering graduate who received a call from the industry for an interview several months after graduation. So he was practicing the recursion method and he wants to test his skills on numbers.

he found a set of numbers that has to be fed into a storage device where the sum of digits of numbers has to be found for memory management in the storage device. 

So the task to find the sum of digits in a number using functions.

Input:
A Integer input represents “num”.

Output:
The sum of digits.
#include <stdio.h>
int sum(int);
int main()
{
  int n;
  scanf("%d",&n);
  printf("%d",sum(n));
  return 0;
}
int sum(int num)
{
  int r,sum=0;
  while(num!=0){
    r=num%10;
    sum+=r;
    num/=10;
  }
  return sum;
}

INPUT_1:
12345

OUTPUT:
15


INPUT_2:
986754

OUTPUT:
39


INPUT_3:
56982

OUTPUT:
30



INPUT_4:
124421

OUTPUT:
14


INPUT_5:
11111

OUTPUT:
5


INPUT_6:
89998

OUTPUT:
43


ILLUSTRATION

EXECUTED USING GCC

Morae Q!