C++ code for sum of digits of a given number

This program will find out sum of digits of a given number.For example: Given number is 341.Then output will be 3+4+1=8.

#include
#include
void main()
{
int n,r,sum=0;
clrscr();
cout<<"Enter a number:";
cin>>n;
while(n>0)
{
r=n%10;
n=n/10;
sum=sum+r;
}
cout<<"nSum of the digits of given number is:"<getch();
}

Output:

Enter a number:341
Sum of digits of given number is:8

Add Comment