Thursday 9 June 2016

Sum of digits of a number

Sum of digits of 1234 = 1 + 2  + 3 + 4 = 10

Code

#include<stdio.h>

int main()
{
     int sum=0,rem,no;

     printf("Enter a number ");
     scanf("%d",&no);

     while(no != 0)
     {
         rem = no % 10;
         sum = sum + rem;
         no = no/10;
     }
     printf("\nSum of the digits = %d",sum);

     return 0;
}

O/P




Code Tracing



Let no = 1234
rem = 1234 % 10 = 4
sum = 0 + 4 = 4
n = 1234/10 = 123 (n is integer)

rem = 123 % 10 = 3
sum = 4 + 3 = 7
n = 123/10 = 12

rem = 12 % 10 = 2
sum = 7 + 2 = 9
n = 12/10 = 1

rem = 1 % 10 = 1
sum = 9 + 1 = 10
n = 1/10 = 0  (STOP)

No comments:

Post a Comment