Sum of digit in C

Program to find sum of digits

Sum of digit in C

We can write the sum of digits program in c language with the help of loop and mathematical operation only. Let’s move forward to write the logic of the program to compute the sum of digits in a given integer.

#include <stdio.h>
void main()
    long num, temp, digit, sum = 0;
printf("\n\t\t\t...Welcome To EduNews.Tech... ");
    printf("\n\nEnter the number : ");
    scanf("%ld", &num);
    temp = num;
    while (num > 0)
        digit = num % 10;
        sum  = sum + digit;
        num /= 10;
    printf("Given number is  = %ld\n", temp);
    printf("Sum of the digits %ld = %ld\n", temp, sum);
printf("\n\n\n\t\t\tThankyou for Joining Us !");
    printf("\n\t\t\t!Regards EduNews !");

Program Output:

sum of digit

Program Explanation-

  1. Take an integer as an 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 a 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.

I hope this post helps you to understand the Sum of digit program and its implementation in C programming language.

Keep coding 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *