Friday, 30 January 2015

Find out the sum of digit in c language.

Sum of the digit


For example if the input is 98, sum(variable) is 0 initially
98%10 = 8 (% is modulus operator which gives us remainder when 98 is divided by 10).
sum = sum + remainder
so sum = 8 now.
98/10 = 9 because in c whenever we divide integer by another integer we get an integer.
9%10 = 9
sum = 8(previous value) + 9
sum = 17
9/10 = 0.
So finally n = 0, loop ends we get the required sum.

C programming code

#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();
}
 
 

Output of program:


 

Make money from your Website or Blog with BidVertiser

No comments:

Post a Comment