7️⃣C Program to Find the Sum of Digits of a Number (With Program and Explanation)

 

๐Ÿ”ข C Program to Find the Sum of Digits of a Number

๐Ÿ“Œ Problem Statement

Write a C program to find the sum of digits of a given number.

Example

If the input number is 456,
then the sum of digits = 4 + 5 + 6 = 15


๐Ÿ’ก Concept Used

In C, we use:

  • % 10 → to extract the last digit of a number

  • / 10 → to remove the last digit

We repeat this process using a while loop until the number becomes 0.


๐Ÿง  Algorithm

  1. Start

  2. Read an integer number

  3. Initialize sum = 0

  4. While the number is greater than 0

    • Find last digit using num % 10

    • Add digit to sum

    • Remove last digit using num / 10

  5. Print the sum

  6. End


๐Ÿ’ป C Program: Sum of Digits of a Number

#include <stdio.h> int main() { int num, digit, sum = 0; printf("Enter a number: "); scanf("%d", &num); while (num > 0) { digit = num % 10; // Extract last digit sum = sum + digit; // Add digit to sum num = num / 10; // Remove last digit } printf("Sum of digits = %d", sum); return 0; }

▶️ Output Examples

✅ Example 1

Input:

Enter a number: 1234

Output:

Sum of digits = 10

✅ Conclusion

In this program, we learned how to calculate the Sum of Digits of a Number in C.


๐Ÿ“˜ C Programming Series – What’s Next?

๐Ÿ‘‰ In the next post of this series, we will learn how to Find GCD of Two Numbers with complete explanation and output examples. Stay tuned! ๐Ÿš€

Comments

Popular posts from this blog

⓮C Program to calculate Simple Interest (With Program and Explanation)

⑫ C Program to Swap Two Numbers Without Using a Temporary Variable (With Program and Explanation)

9️⃣C Program to Find LCM of Two Numbers (With Program and Explanation)