Wednesday, December 1, 2010

Algorithm, Program & Output for Sum of digits of a number

Algorithm
  1. Start
  2. Read a number ‘n’
  3. Assign m with n, sum with 0
  4. If n ≠ 0 repeat steps (5) thru (7) else go to (8)
  5. k ß modulus(n,10)
  6. sum ß sum + k
  7. n ß quotient of n/10
  8. Print sum of digits of n is sum
  9. Stop
Program
#include <stdio.h>

main()
{
            int n,m,k,sum ;

            clrscr() ;
            printf("\tProgram to find Sum of Digits of a Number\n") ;
            printf("\n  Input\n\n") ;
            printf("Enter a Number : ") ;
            scanf("%d",&n) ;
            m = n ;
            sum = 0 ;
            while (n != 0)
              {
                  k = n%10 ;
                  sum += k ;
                  n = n/10 ;
              }
            printf("\n  Output\n\n") ;
            printf("Sum of Digits of %d is : %d",m,sum) ;
            getch() ;
}


Output
     Program to find Sum of Digits of a Number

  Input

Enter a Number : 1729

  Output

Sum of Digits of 1729 is : 19

       Program to find Sum of Digits of a Number

  Input

Enter a Number : -786

  Output

Sum of Digits of -786 is : -21

No comments:

Post a Comment