This is a C program to compute the sum of digits in a given integer.
This program computes the sum of digits in a given integer.
1. Take the integer as input.
2. Divide the input integer by 10, obtain its remainder and quotient.
3. Increment the new variable with the remainder got at step 2.
4. Repeat the step 2 & 3 with the quotient obtained until the qoutient becomes zero.
5. Print the output and exit.
Here is source code of the C program to compute the sum of digits in a given integer. The C program is successfully compiled and run on a Linux system. The program output is also shown below.
* C program to accept an integer & find the sum of its digits
long num, temp, digit, sum = 0;
printf("Enter the number \n");
temp = num;
while (num > 0)
digit = num % 10;
sum = sum + digit;
num /= 10;
printf("Given number = %ld\n", temp);
printf("Sum of the digits %ld = %ld\n", temp, sum);
1. Take an integer as a input and store it in the variable num.
2. Initialize the variable sum to zero.
3. Divide the input integer by 10 and obtain its remainder & quotient.
4. Store the remainder in the variable digit.
5. Increment the variable sum with variable digit.
6. Store the quotient into the variable num.
7. Repeat the steps 3,4,5,6 with the new num.
8. Do step 7 until the quotient becomes zero.
9. Print the variable sum as output and exit.
Enter the number 300 Given number = 300 Sum of the digits 300 = 3 Enter the number 16789 Given number = 16789 Sum of the digits 16789 = 31
Sanfoundry Global Education & Learning Series – 1000 C Programs.