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

Write a program that prints the sum of digits of a number using for loop.

👁 25,838 Views
💻 Practical Program
📘 Step by Step Learning
Write a program that prints the sum of digits of a number using for loop.

Program Code

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

Output


 Enter the Number: 123

 Sum of digits 6

Explanation

None

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.