Sum of digits program in C

C program to sum each digit: We can write the sum of digits program in c language by the help of loop and mathematical operation only.

Sum of digits algorithm

To get sum of each digits by c program, use the following algorithm:

  • Step 1: Get number by user
  • Step 2: Get the modulus/remainder of the number
  • Step 3: sum the remainder of the number
  • Step 4: Divide the number by 10
  • Step 5: Repeat the step 2 while number is greater than 0.

Let's see the sum of digits program in C.

  1. #include<stdio.h>  
  2.  int main()    
  3. {    
  4. int n,sum=0,m;    
  5. printf("Enter a number:");    
  6. scanf("%d",&n);    
  7. while(n>0)    
  8. {    
  9. m=n%10;    
  10. sum=sum+m;    
  11. n=n/10;    
  12. }    
  13. printf("Sum is=%d",sum);    
  14. return 0;  
  15. }   

Output:

Enter a number : 654
Sum is = 15
Enter a number : 123 
Sum is = 6 
Previous Post Next Post