Sum of the Digits

Write a program that reads a number and prints the sum of its digits. Use the division (/) operator and the remainder (%) operator.

using namespace std;
int main(){
	int n,sum=0,d;
	cout<<"Enter the number : ";
		d = n%10;
		sum = sum + d;
		n = n/10;
	cout<<"The sum is "<<sum<<endl;
	return 0;

Here, d gets the remainder. The remainder is added to the sum. Then n is reduced by 10. This is done till n becomes 0 and it gets out of loop.

output showing sum of integers
output showing sum of integers

Leave a Reply