C program to find sum of digits of a number

Write a C program to enter any number and calculate sum of digits of number using for loop. C program to find sum of digits of a number. How to find sum of digits of a number in C programming.

Example:
Input any number: 1234
Output sum of digits: 1 + 2 + 3 + 4 = 10

Required knowledge:

Basic C programming, While loop

Logic to find sum of digits

Before moving on to the logic of finding sum of digits one thing you must be done with is how to find the last digit of any number in C. Now, moving on to logic of this program can be divided in three basic steps:
  1. Find the last digit of number by performing modular division.
  2. Add the last digit just found above to sum.
  3. Remove the last digit from number by dividing the number by 10.
Repeat the above three steps till the number becomes 0 and you will be left with the sum of digits.

Program to find sum of digits

/**
 * C program to find sum of its digits of a number
 */

#include <stdio.h>

int main()
{
    int num, sum=0;

    /* Reads a number from user */
    printf("Enter any number to find sum of its digit: ");
    scanf("%d", &num);

    /* Repeat till num becomes 0*/
    while(num!=0)
    {
        /* Find the last digit of num and add to sum */
        sum += num % 10;

        /* Removes last digit from num */
        num = num / 10;
    }

    printf("\nSum of digits = %d", sum);

    return 0;
} 


Output
X
_
Enter any number to find sum of its digit: 1234

Sum of digits = 10

Happy coding ;)


Any doubt or suggestion write here. I will try my best to help. Before posting your code you must escape it to view. To format your source code and use format highlighting, post your source code inside
< code >< pre > -- Your source code -- < /pre >< /code > (Remove spaces from pre and code tags).

No comments:

Post a Comment