C Program to Find Sum of Digits of a Number, let’s see how can we solve this problem in C Language.
Table of Contents
Algorithm to Calculate Sum of Digits of a Number
- Our C program needs the number as its target. We’ll use
scanf
to accept it from the user, storing it in a variable namednumber
- Now we have to calculate the total no of digits present in the given number
- Extract each digit of the number by using the ‘%’ operator
- Add the extracted digit to the variable names
sum
- Print the variable
sum
C Program to Calculate Sum of Digits of a Number
#include <stdio.h>
void main()
{
int number, sum = 0, digits = 0;
printf("Enter the number ");
scanf("%d", &number);
int temp = number;
while (temp > 0)
{
digits++;
temp /= 10;
}
for (int i = 1; i <= digits; i++)
{
int remainder = number % 10;
sum += remainder;
number /= 10;
}
printf("sum of the digits of given number = %d ", sum);
}
Output
Happy Coding
5 thoughts on “C Program to Find Sum of Digits of a Number”