C program to find sum of digits of a number

Previous Program Next Program

Write a C program to enter any number and calculate sum of digits 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. Logic to find sum of digits of a given number in C program.

Example

Input

Input any number: 1234

Output

Sum of digits: 10

Required knowledge

Basic C programming, While loop

Logic to find sum of digits

The main idea to find sum of digits can be divided in three steps -

  1. Extract the last digit.
  2. Add the extracted last digit to sum.
  3. Remove the last digit. As it is processed and not required any more.
  4. If you repeat above three steps till the number becomes 0. Finally you will be left with sum of digits.

Below is the step by step descriptive logic to find sum of digits.

  1. Read number from user. Store it in some variable say num.
  2. Find the last digit by performing modular division i.e. digit = num % 10.
  3. Add the last digit just found above to sum i.e. sum = sum + digit.
  4. Remove the last digit from number by dividing the number by 10. Which is num = num / 10
  5. Repeat step 2-4 till number becomes 0. Finally 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;

    /* Read 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("Sum of digits = %d", sum);

    return 0;
} 
Output
Enter any number to find sum of its digit: 1234
Sum of digits = 10

Happy coding ;)

You may also like

Previous Program Next Program
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
< pre>< code >----Your Source Code---- < / code > < / pre > (Remove spaces from pre and code tags)

No comments:

Post a Comment