Sum of Digits Program
Written by
Sum of digits of a number:
The code for calculating the sum of digits of a number is:
#include <stdio.h>int main()
{
int num;
int remainder;
int sum = 0;
printf("Enter an integer: ");
scanf("%d", & amp; num);
while (num != 0)
{
remainder = num % 10; //Extracting digit sum = sum + remainder; num = num / 10;
}
printf("Sum of digits of is: %d \n", sum);
return 0;
}
The output for the above code is:
Enter an integer: 1111Sum of digits of is: 4
- We have created the variable num to store the user input and the variable sum to store the sum of the digits of the number entered by the user.
- The while loop runs until num is not equal to 0.
- In each iteration, we calculate the remainder when num is divided by 10. The value of num is then reduced by 10 times. The remainder we get in each iteration is a digit. We add this digit to sum.
- At the end of the loop, we get the sum of all the digits in the number.
When we input 1234 for the above code, the intermediate steps and the output will be:
Enter an integer: 1234During iteration:
remainder: 4
sum: 4
remainder: 3
sum: 7
remainder: 2
sum: 9
remainder: 1
sum: 10
Sum of digits of is: 10