#include <stdio.h>
int main() {
long long n, sum = 0, digit;
scanf("%lld", &n);
while (n > 0) {
digit = n;
while (digit > 0) {
sum = sum + digit % 10;
digit = digit / 10;
}
n = n - 1;
}
printf("%lld", sum);
return 0;
}
This program calculates the sum of all digits of all numbers from 1 down to the input number n. For example, if n is 3, it sums digits of 3, 2, and 1 (3+2+1=6). The outer loop decreases n by 1 each iteration, and the inner loop extracts and sums the digits of the current n.
- The outer loop condition `while (n > 0)` will stop when n reaches 0, but note that the inner loop modifies `digit` which is a copy of n, so the outer loop's n is not affected by the inner loop's changes.
- Consider what happens when n is a large number like 1000000000. The program will iterate through every integer from n down to 1, which may be very slow. Think about whether there is a more efficient way to compute the sum of digits for a range of numbers without processing each number individually.