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

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

Algorithm
  1. Start
  2. Read a number ‘n’ > 0
  3. Assign sum with 0, i with 1
  4. If i<=n then repeat steps (5) and (6) else go to (7)
  5. If modulus(n,i) = 0
then sum ß sum + i and go to (6)
else go to (6)
  1. i ß i + 1
  2. Print sum of factors of n is sum
  3. Stop
 Program
#include <stdio.h>

main()
{
            int n,i,sum ;

            clrscr() ;
            printf("\tProgram to find Sum of factors of a Number\n") ;
            printf("\n  Input\n\n") ;
            printf("Enter a Number : ") ;
            scanf("%d",&n) ;
            sum = 0 ;
            for (i=1;i<=n;i++)
                if ((n%i) == 0)
                        sum += i ;
            printf("\n  Output\n\n") ;
            if (n <= 0)
                        printf("Enter greater than Zero") ;
            else
                        printf("Sum of factors of %d is : %d",n,sum) ;
            getch() ;
}


Output

Program to find Sum of factors of a Number

  Input

Enter a Number : 36

  Output

Sum of factors of 36 is : 91

Program to find Sum of factors of a Number

  Input

Enter a Number : 0

  Output

Enter greater than Zero