C Program to find sum of number digit using recursion

Ans: 

In this tutorial you will learn how to write a program in C to sum the digits of a number using recursion.

Basically our target is to add all digits of any given number.

Suppose If someone will give input 1547 then our program should give output after adding 1, 5, 4, and 7.

1+5+4+7 = 17.

So our program should print output as 17.

How our program will behave?

Our program will take a number as an input and it should give the output after addition of all the digits of a given number.

If someone has given input of 143 then our program should give 8 as a output.

C Program to add the digits of a given number using recursive function

#include<stdio.h>
#include<conio.h>
int sumOfDigits(int num) {
  static int sum = 0;
  int rem;
  sum = sum + (num % 10);
  rem = num / 10;
  if (rem > 0) {
    sumOfDigits(rem);
  }
  return sum;
}
int main() {
  int j, num;
  printf("Please enter a number :");
  scanf("%d", & num);
  printf("sum of digits of the number = %d ", sumOfDigits(num));
  getch();
}

Output 1:

Please enter a number :3214
sum of digits of the number = 10

Output 2:

Please enter a number :4556
sum of digits of the number = 20 

Explanation of the above program

  • In the above program inside sumOfDigits() method we have one static integer variable ‘sum’ and one integer variable ‘rem’.
  • And in main() method we have two int variable j and num.
  • sumOfDigits(int num) is recursive method that will return the sum of digits.
  • Inside sumOfDigits(int num) method we have first finding the last digit of the number. After that we are dividing number by 10 to find next digit.
  • As you can see ‘sum’ variable is declared as static. It is static because method is calling itself again and again, and if we won’t declare ‘sum’ as static then each time it will reassign to 0 and lost the previous value. So static will help to protect its previous value.

I hope you have understood it.

Leave a Comment