Complementary task for topic: 10

M Nemeth · 2023-08-29 15:21:04.632218'

Recursion: sum of digits

Recursion: sum of digits

Write a program to calculate the sum of digits of a positive integer using recursion.

Hint: We know that:
sumofdigit(124324)=4+sumofdigit(12432)... So here is the recursion. We also know the sum of digits for zero.

Solution
#include 

// Function to calculate the sum of digits using recursion
int sumOfDigits(int num) {
    if (num == 0) {
        return 0;
    } else {
        return (num % 10) + sumOfDigits(num / 10);
    }
}

int main() {
    int num;
    printf("Enter a positive integer: ");
    scanf("%d", &num);

    if (num < 0) {
        printf("Error: The number should be a positive integer.\n");
    } else {
        int result = sumOfDigits(num);
        printf("The sum of digits of %d is: %d\n", num, result);
    }

    return 0;
}



Explanation

< < previous    next > >