Ads Top

TECHASHUS -ADD DIGITS OF NUMBER IN C




C program to add digits of a number: Here we are using modulus operator(%) to extract individual digits of number and adding them.

PROGRAM:

#include <stdio.h>
 
int main()
{
   int n, t, sum = 0, remainder;
 
   printf("Enter an integer\n");
   scanf("%d", &n);
 
   t = n;
 
   while (t != 0)
   {
      remainder = t % 10;
      sum       = sum + remainder;
      t         = t / 10;
   }
 
   printf("Sum of digits of %d = %d\n", n, sum);
 
   return 0;
}

OUTPUT :

 Enter An Integer
12345
Sum of Digits of  12345 =  15


For example if the input is 98, sum(variable) is 0 initially
98%10 = 8 (% is modulus operator which gives us remainder when 98 is divided by 10).
sum = sum + remainder
so sum = 8 now.
98/10 = 9 because in c whenever we divide integer by another integer we get an integer.
9%10 = 9
sum = 8(previous value) + 9
sum = 17
9/10 = 0.
So finally n = 0, loop ends we get the required sum.

Find sum of digits in c without modulus operator

C program to find sum of digit of an integer which does not use modulus operator. Our program uses a character array (string) for storing an integer. We convert every character of string into an integer and add all these integers.

PROGAM :

#include <stdio.h>
 
int main()
{
   int c, sum, t;
   char n[1000];
 
   printf("Input an integer\n");
   scanf("%s", n);
 
   sum = c = 0;
 
   while (n[c] != '\0') {
      t   = n[c] - '0'; // Converting character to integer
      sum = sum + t;
      c++;
   }
 
   printf("Sum of digits of %s = %d\n", n, sum);
 
   return 0;
}

An advantage of this method is that input integer can be very large which may not be stored
 in int or long long data type see an example below in output.

OUTPUT :
Input an integer
123456789123456789123456789
Sum of digits of 123456789123456789123456789 = 135

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


Static variable sum is used and is initialized to 0, it' value will persists after function calls i.e. it is initialized only once when a first call to function is made.

No comments:

Powered by Blogger.