Home / Programs / Write a program that prints the sum of digits of a number.
Programming Example

Write a program that prints the sum of digits of a number.

👁 1,141 Views
💻 Practical Program
📘 Step by Step Learning
Write a program that prints the sum of digits of a number.

Program Code

#include <stdio.h>
int main()
{
	int n, s=0, r;
	printf("\n Enter the Number: ");
	scanf("%d", &n);
	while(n>0)
	{
		r=n%10;
		s=s+r;
		n=n/10;
	}
	printf("\nSum of digits %d", s);
	
	getch();
	return 0;
}

Output

<b>Output 1:</b>

 Enter the Number: 123

Sum of digits 6

<b>Output 2</b>

 Enter the Number: 1111

Sum of digits 4

Explanation

Example: Number: 123 1+2+3 = 6

How to learn from this program

First read the algorithm, then study the program code line by line. After that, compare the code with the output and finally go through the explanation. This approach helps learners understand both the logic and the implementation properly.