In this article, we will write a C program to find sum of digits of a given number. For example, if the input number is 345 then the output of the program should be 3+4+5 = 12.
C Program to print sum of digits of a number
Detailed explanation of the logic is provided at the end of the program.
#include <stdio.h>
int main() {
int number, sum = 0, digit;
// Input the number
printf("Enter a number: ");
scanf("%d", &number);
// Loop to add all the digits of number to sum
while (number != 0) {
digit = number % 10; // find the last digit
sum += digit; // Add this digit to sum
number /= 10; // Remove the last digit
}
// Display the sum
printf("Sum of digits: %d\n", sum);
return 0;
}
This programs prompts the user to enter an integer number. It iterates through all the digits of the entered number using while loop, at every iteration, it adds the last digit to the variable sum
. It also removes the last digit after this so that on next iteration, the second last digit gets processed. At the end it displays the value of sum
, which contains the addition of all digits.
Output:
Enter a number: 12345
Sum of digits: 15
User entered the number 12345, the sum of its digits (1+2+3+4+5) is 15.
Detailed explanation of the program
The while loop in the program continues to execute as long as the condition number != 0
holds true. Let’s break down the logic inside the loop step by step:
- Finding the last digit:
- In each iteration, the statement
digit = number % 10;
calculates the remainder whennumber
is divided by 10. This gives us the last digit of the number. - For example, if
number
is 12345, thennumber % 10
will result in 5.
- In each iteration, the statement
- Adding the digit to the sum:
- The line
sum += digit;
adds the last digit to thesum
variable. - In this example,
sum
was initially 0 and the extracted digit is 5, thensum
becomes 0 + 5 = 5.
- The line
- Removing the last digit:
- After finding the last digit and adding it to the sum, we need to remove it from the number so that the next iteration add the second last digit of the number to the variable sum.
- This is done by the statement
number /= 10;
, which dividesnumber
by 10, effectively removing the last digit. - For example, if
number
was 12345, thennumber /= 10;
changesnumber
to 1234.
- Loop continuation and termination:
- The loop continues iterating as long as
number
is not equal to 0. This means that once all the digits have been added to the sum,number
becomes 0, and the loop terminates. At this point the variable sum holds the sum of all the digits of thenumber
.
- The loop continues iterating as long as
Leave a Reply