use C program Write a method that computes the sum of the digits in an integer. Use the following method header: int sumDigits(int n)
时间: 2024-02-27 14:58:30 浏览: 84
sum of Digit
Sure, here's a C program that implements the `sumDigits` method as described:
```c
#include <stdio.h>
int sumDigits(int n);
int main() {
int n;
printf("Enter an integer: ");
scanf("%d", &n);
printf("The sum of digits in %d is %d\n", n, sumDigits(n));
return 0;
}
int sumDigits(int n) {
int sum = 0;
while (n != 0) {
int digit = n % 10;
sum += digit;
n /= 10;
}
return sum;
}
```
The `sumDigits` method takes an integer `n` as input, and returns the sum of the digits in `n`. The main function prompts the user to input an integer, calls `sumDigits` to compute the sum of its digits, and prints the result. The `sumDigits` method uses a while loop to iterate over each digit in `n`, adding it to a running total until all digits have been processed.
阅读全文