Challenge: Count the Digits
Completed
Read a positive whole number and print how many digits it has, and the sum of its digits.
Input
One positive integer.
Output
Digits: D, Sum: S
Example
Input
4827
Output
Digits: 4, Sum: 21
Editor
C
Hints
n % 10 is the last digit.
n / 10 removes the last digit.
Repeat while n > 0.
Solution explanation
Each round takes off the last digit with % 10, adds it, then removes it with / 10.
Show solution
#include <stdio.h>
int main() {
int n;
scanf("%d", &n);
int digits = 0;
int sum = 0;
while (n > 0) {
sum += n % 10;
n /= 10;
digits++;
}
printf("Digits: %d, Sum: %d\n", digits, sum);
return 0;
} Output
Answer
You can practice without logging in. Log in to save completion.
Save your progress
You're practising as a guest, so your progress won't be saved.
- Track every lab you complete
- Earn verifiable lab certificates
- See your progress in every module