C Program to Find Sum of Digits of a Number using Recursion
Write a C program to find sum of digits of a number using recursion.
- The function sum_of_digits() recursionly calculates the sum of digits of an integer.
- Base case: if n is 0, it returns 0 (termination condition).
- Recursion case: it adds the last digit n % 10 to the result of the recursion call with n / 10.
- The main function passes the number 1234 and prints the total sum returned by the recursion function.
Example : pgm.c
#include <stdio.h> int sum_of_digits(int n) { // Base case if (n == 0) return 0; // Recursion case return (n % 10) + sum_of_digits(n / 10); } int main() { int number = 1234; printf("Sum of digits of %d is %d\n", number, sum_of_digits(number)); return 0; }
Output :
Sum of digits of 1234 is 10