C program to find the sum of digit using array:
In this C tutorial we learn C program to find the sum of digit(s) of an integer that does not use modulus operator. Our program uses a character array (string) for storing an integer. We convert every character of the string into an integer and add all these integers.
#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;
}
Sum of digits of a number in C
int main()
{
int n, temp, sum = 0, remainder;
printf("Enter an integer\n");
scanf("%d", &n);
temp = n;
while (temp != 0)
{
remainder = temp % 10;
sum = sum + remainder;
temp = temp / 10;
}
printf("Sum of digits of %d = %d\n", n, sum);
return 0;
}
Sum of digits of a number C program using recursion:-
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;
}