Thursday, July 26, 2012

Sum digits of a number

1. Iterative:
The function has three lines instead of one line but it calculates sum in one line. It can be made one line function if we pass pointer to sum.
# include<stdio.h>
int main()
{
  int n = 687;
  printf(" %d ", getSum(n));
 
  getchar();
  return 0;
}
 
/* 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;
}

2. Recursive
Thanks to ayesha for providing the below recursive solution.
int sumDigits(int no)
{
  return no == 0 ? 0 : no%10 + sumDigits(no/10) ;
}
 
int main(void)
{
  printf("%d", sumDigits(1352));
  getchar();
  return 0;
}

No comments:

Post a Comment