Complementary task for topic: 4

M Nemeth � 2023-08-29 15:21:04.617219'

Functions: Sum of Digits

Functions: Sum of Digits

Write a C function sum_of_digits that takes an integer as input and returns the sum of its digits.

Hint:

Solution
#include 
 
// Function to calculate the sum of digits
int sum_of_digits(int num) {
    int sum = 0;
    while (num != 0) {
        sum += num % 10;
        num /= 10;
    }
    return sum;
}
 
int main() {
    int num;
    printf("Enter a number to calculate the sum of its digits: ");
    scanf("%d", &num);
 
    int result = sum_of_digits(num);
    printf("Sum of digits of %d is %d.\n", num, result);
 
    return 0;
}
 
 


Explanation
The sum_of_digits function takes an integer num as input and calculates the sum of its digits using a while loop. It extracts the last digit of num using the modulus operator (%) and adds it to the sum. Then, it removes the last digit from num by dividing it by 10 (num /= 10). The loop continues until num becomes 0. The function returns the final sum of digits.
< < previous    next > >