C Programs | IT Developer
IT Developer

C Programs



Share with a Friend

Functions in C

Recursive Function to print sum of digits of a number

C Program: Recursive Function to print sum of digits of a number

C

#include <stdio.h>

 

// Function declaration

int sumOfDigits(int num);

 

int main() {

    int number;

 

    // Input number

    printf("Enter a number: ");

    scanf("%d", &number);

 

    // Function call and display result

    printf("Sum of digits of %d = %d\n", number, sumOfDigits(number));

 

    return 0;

}

 

// Recursive function to calculate sum of digits

int sumOfDigits(int num) {

    if (num == 0)

        return 0;  // Base condition

    return (num % 10) + sumOfDigits(num / 10);

}

Output

 
OUTPUT 1 :
Enter a number: 1234
Sum of digits of 1234 = 10

OUTPUT 2 :
Enter a number: 987
Sum of digits of 987 = 24

Explanation

  1. Recursive Concept
    • Every time the function is called, it separates the last digit using num % 10.
    • Adds that digit to the result of sumOfDigits(num / 10).
    • When num becomes 0, recursion stops (base case).
  2. Flow Example (for 1234)

           sumOfDigits(1234)

           = 4 + sumOfDigits(123)

           = 4 + 3 + sumOfDigits(12)

           = 4 + 3 + 2 + sumOfDigits(1)

           = 4 + 3 + 2 + 1 + sumOfDigits(0)

           = 10