Loading...

Add Digits of a number C Program


C Program which take a number as a input and print the sum of its digits:

#include <stdio.h>
main()
{
   int n, sum = 0, remainder;

   printf("Enter an integer: ");
   scanf("%d",&n);

   while(n != 0)
   {
      remainder = n % 10;
      sum = sum + remainder;
      n = n / 10;
   }

   printf("Sum of digits = %d",sum);
}


Also by Making Function of it:


#include <stdio.h>
void sumofdigits(int);
main()
{
    int n;

    printf("Enter an integer: ");
    scanf("%d",&n);

    sumofdigits(n);
}
void sumofdigits(int n)
{
    int sum = 0, remainder;

    while(n != 0)
    {
        remainder = n % 10;
        sum = sum + remainder;
        n = n / 10;
    }

    printf("Sum of digits = %d",sum);
}

Rate this posting:
{[['']]}

0 comments:

Post a Comment

 
TOP