C program to find sum of digits of a five digit number

CServer Side ProgrammingProgramming

Suppose we have a five-digit number num. We shall have to find the sum of its digits. To do this we shall take out digits from right to left. Each time divide the number by 10 and the remainder will be the last digit and then update the number by its quotient (integer part only) and finally the number will be reduced to 0 at the end. So by summing up the digits we can get the final sum.

So, if the input is like num = 58612, then the output will be 22 because 5 + 8 + 6 + 1 + 2 = 22.

To solve this, we will follow these steps −

  • num := 58612
  • sum := 0
  • while num is not equal to 0, do:
    • sum := sum + num mod 10
    • num := num / 10
  • return sum

Example

Let us see the following implementation to get better understanding −

#include <stdio.h>
int main(){
    int num = 58612;
    int sum = 0;
   
    while(num != 0){
        sum += num % 10;
        num = num/10;
    }
    printf("Digit sum: %d", sum);
}

Input

58612

Output

Digit sum: 22
raja
Published on 08-Oct-2021 11:00:17
Advertisements