Write+a+program++in+c+that+calculates+the+sum+of+the+digits+of+a+positive+integer+typed+in+from+the+keyboard.+For+example
时间: 2023-11-08 18:05:16 浏览: 105
Sure! Here's an example program in C that calculates the sum of the digits of a positive integer typed in from the keyboard:
```
#include <stdio.h>
int main() {
int num, sum = 0, digit;
printf("Enter a positive integer: ");
scanf("%d", &num);
while (num > 0) {
digit = num % 10;
sum += digit;
num /= 10;
}
printf("The sum of the digits is %d\n", sum);
return 0;
}
```
This program first prompts the user to enter a positive integer, then reads in the integer using `scanf()`. It then uses a `while` loop to repeatedly extract the rightmost digit of the integer using the modulus operator `%`, add it to a running sum, and remove that digit from the integer by dividing by 10. Once the entire integer has been processed, the program prints out the final sum.
I hope that helps! Let me know if you have any further questions.
阅读全文