# Sum of digits program in C

Certainly! Here’s an example of a program in C that calculates the sum of the digits of a given integer:

```#include <stdio.h>

int sumOfDigits(int number) {
int sum = 0;

while (number != 0) {
sum += number % 10;  // Add the last digit to the sum
number /= 10;       // Remove the last digit from the number
}

return sum;
}

int main() {
int number;

printf("Enter an integer: ");
scanf("%d", &number);

int result = sumOfDigits(number);
printf("The sum of the digits is: %d\n", result);

return 0;
}
```

In this program, the `sumOfDigits` function takes an integer `number` as input and calculates the sum of its digits. It uses a while loop to iterate through the digits of the number. In each iteration, it adds the last digit to the `sum` variable and removes the last digit from the number by dividing it by 10. The loop continues until the number becomes 0, indicating that all digits have been processed.

In the `main` function, the user is prompted to enter an integer. The `scanf` function is used to read the input from the user and store it in the `number` variable. Then, the `sumOfDigits` function is called with `number` as the argument, and the result is printed.

Please note that this program assumes the input will be a valid integer. Additional input validation could be added to handle invalid inputs.

### Sum of digits algorithm:

Certainly! Here’s an algorithm to calculate the sum of the digits of a given integer:

1. Start with an integer `number`.
2. Initialize a variable `sum` to 0.
3. Repeat the following steps until `number` becomes 0:
• Get the last digit of `number` by taking the remainder of `number` divided by 10.
• Add the last digit to `sum`.
• Update `number` by dividing it by 10, discarding the last digit.
4. The final value of `sum` is the sum of the digits of the original `number`.

Here’s the algorithm represented in pseudocode:

```function sumOfDigits(number):
sum = 0

while number != 0:
lastDigit = number % 10
sum = sum + lastDigit
number = number / 10

return sum
```

You can implement this algorithm in various programming languages like C, Java, Python, etc. by translating the pseudocode into the syntax of the specific language.

Categories C