Question:Sum of digits in c using recursion 

Answer 
#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;
}
Sample output: Enter a number: 45 Sum of digits of number: 9 

+ Report
Total Preview: 458
Sum of digits in c using recursion
Copyright © 2024. Powered by Intellect Software Ltd