C Program to find the sum of digits of a number | Using while loop

C Program to find the sum of digits of a number | Using while loop

C Program to find the sum of digits of a number
In this example, we will learn how to find the sum of all digits of a number in C. Our program will take one number as input from the user, calculate the sum of its digits and print it out. We will use while loop to find the digits of the given number and use one variable to store the sum of all the digits.
For example if user enters the the number 4538, then output i.e. sum of digits will be equal to 20. (4+5+3+8=20)

C Program to find the sum of digits of a number:
#include<stdio.h>  
 int main()    
{    
int n,sum=0,m;    
printf("Please Enter any Number: ");    
scanf("%d",&n);    
while(n>0)    
{    
m=n%10;    
sum=sum+m;    
n=n/10;    
}    
printf("Sum of the digits of Given Number = %d"sum);    
return 0;  
}  

Output:
Please Enter any Number: 4538 Sum of the digits of Given Number = 20

Run Code: If you want run this code copy this code, paste here and run.

No comments: