Sum of digits in c using recursion

Posted By: Matpal Media - 1:35 AM
#include<stdio.h>

int getSum(int);
int main(){
  int num,sum;
  printf("Enter a number: ");
  scanf("%d",&num);

  sum = getSum(num);

  printf("Sum of digits of number:  %d",sum);
  return 0;
}

int getSum(int num){

    static int sum =0,r;

    if(num!=0){
      r=num%10;
      sum=sum+r;
      getSum(num/10);
    }

    return sum;
}

0 comments:

Post a Comment

Note: Only a member of this blog may post a comment.