Programming Example
Write a program that prints the sum of digits of a number.
Write a program that prints the sum of digits of a number.
#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;
}
<b>Output 1:</b>
Enter the Number: 123
Sum of digits 6
<b>Output 2</b>
Enter the Number: 1111
Sum of digits 4
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.
After understanding this example, try to rewrite the same program without looking at the code. Then change some values or logic and run it again. This helps improve confidence and keeps learners engaged on the page for longer.