#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
*/