How to calculate the sum of digits and count the digits of a number in C

2 Answers

0 votes
#include <stdio.h>
 
int main(void)
{
    int n = 12345, sum = 0, count = 0;
  
    while (n > 0) {
        sum += n % 10;
        n = n / 10;
        count++;
    }
    
    printf("sum = %i count = %i", sum, count);
             
    return 0;
}
 
 
/* 
run:
 
sum = 15 count = 5

*/


answered Sep 17, 2014 by avibootz
edited Oct 29 by avibootz
0 votes
#include <stdio.h>
#include <stdlib.h> // Required for llabs() to handle negative numbers

/**
 * Calculates both the sum and count of digits of a given number.
 * 
 * @param number The input number (supports positive, negative, and zero).
 * @param sum    Pointer to store the calculated sum of digits.
 * @param count  Pointer to store the calculated count of digits.
 */
void calculate_digit_stats(long long number, int* sum, int* count) {
    // Initialize output variables safely
    *sum = 0;
    *count = 0;

    // Handle negative numbers by converting to their absolute value
    number = llabs(number);

    // Special case for zero: count is 1, sum is 0
    if (number == 0) {
        *sum = 0;
        *count = 1;
        return;
    }

    // Extract digits iteratively from right to left
    while (number > 0) {
        int digit = number % 10; // Extract the last digit
        *sum += digit;           // Add to sum
        (*count)++;              // Increment digit count
        number /= 10;            // Remove the last digit
    }
}

int main() {
    // Test with a negative multi-digit number
    long long test_number = -98765;
    int digit_sum = 0;
    int digit_count = 0;

    // Call the function passing addresses of sum and count
    calculate_digit_stats(test_number, &digit_sum, &digit_count);

    // Output the results
    printf("Number: %lld\n", test_number);
    printf("Sum of digits: %d\n", digit_sum);
    printf("Count of digits: %d\n", digit_count);

    return 0;
}
 
 
/* 
run:
 
Number: -98765
Sum of digits: 35
Count of digits: 5

*/

 



answered Oct 29 by avibootz

Related questions

1 answer 332 views
1 answer 216 views
1 answer 210 views
1 answer 214 views
1 answer 199 views
...