To find the sum of digits using recursion
This program returns the sum of digits in a number using recursion.
Logic:
- Get the number from the user.
- Then pass the number as an argument to a function.
- And separate the digits in the number and add the digits.
- Return the sum value.
Algorithm:
- Get the number from the user.
- Then pass the number to a function to implement recursion.
- Take modulo division of the number.
- Then pass the number recursively after dividing the number by 10.
- At last returns the sum of digits.
Program:
#include<stdio.h> void main() { int n; clrscr(); printf("enter the number:"); scanf("%d",&n); /*pass the number into the funtion as an argument*/ printf("sum of digits is: %d",digit(n)); getch(); } int digit(int n) { if(n!=0) { /* take modulo division of the number and then pass the number recursively after dividing the number 10 */ return (n%10)+digit(n/10); } else { return 0;//returns 0 when value of n becomes 0 } }