Wednesday, 21 August 2013

Add digits of number in c


Add digits of number in c

C programming code
#include <stdio.h>

int main()
{
   int n, sum = 0, remainder;

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

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

   printf("Sum of digits of entered number = %d\n",sum);

   return 0;
}

Output of program:

Enter an integer

1234

Sum of digits of entered number =10

2. Add digits using recursion

#include <stdio.h>

int add_digits(int);

int main()
{
  int n, result;

  scanf("%d", &n);

  result = add_digits(n);

  printf("%d\n", result);

  return 0;
}

int add_digits(int n) {
  static int sum = 0;

  if (n == 0) {
    return 0;
  }

  sum = n%10 + add_digits(n/10);

  return sum;
}
-------------------------------**************************----------------------------------------

No comments:

Post a Comment