Sum of Digits in C Program

           Sum of Digits in C Program


{tocify} $title= {Table of Contents}

Sum of Digits in C Program

In this C program, we will code Sum of Digits of a Number in C we will allow the user to enter any number and then we will divide the number into individual digits and add those individuals (sum=sum+digit) digits using While Loop. 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.

Sum of Digits in C Program

For user input num
  1. Initialize sum = 0
  2. Extract the last digit of the number and add it to the sum (sum += num % 10)
  3. Reduce the number  (num = num / 10
  4. Keep doing this until num becomes 0
To get sum of each digits by c program, use   
Ex:-  number is 23145
 2 + 3 + 1 + 4 + 5 = 15
Sum of digit of a given number is 15

C Code

#include<stdio.h>  
 int main()    
{    
int a,sum=0,b;    
printf(“Enter a number:”);    
scanf(“%d”,&n);    
while(n>0)    
{    
b=a%10;    
sum=sum+b;    
a=a/10;    
}    
printf(“Sum is=%d”,sum);    
return 0;  
}   

Output



Post a Comment (0)
Previous Post Next Post