Add the digit of the number.

Hear is the C program to simply  add the digit in the number. First take the input of the number in variable n, then perform the required task.

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;
} 


Hear in the while loop we simply break the number into its digit then We perform
the adition.
rest is easy to unserstand
 

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