C program to calculate the sum of digits of a number

Logic: 

  1. Use modulus operator (%) to extract individual digits of a number 
  2. Keep on adding that digits to sum 
  3. After adding to the sum discard that digit
				
					#include <stdio.h> 
#include<conio.h> 
void main() 
{
int n, t, sum = 0, remainder; 
clrscr();
printf("Enter an integer\n");
scanf("%d", &n); 
t = n;
while (t != 0)  
{
remainder = t % 10; 
sum= sum + remainder;
t= t / 10;  
}
printf("Sum of digits of %d = %d\n", n, sum); 
getch();
}
				
			

Leave a Reply