Quantcast
Channel: C Programming Archives - QnA Plus
Viewing all articles
Browse latest Browse all 93

C Program to Find the Sum of all Digits of a Number

$
0
0

Here we’ll see how to write a C program to find the summation of all digits in a number.

#include <stdio.h>

int sum_digits(int n) {
    int sum = 0;
    while(n) {
	    sum += (n % 10);
	    n /= 10;
	}
	return sum;
}

int main()
{
	int n = 0;
    printf("Enter an integer: ");
    scanf("%d", &n);
    
    printf("Sum of all digits of %d is %d.\n", n, sum_digits(n));
    return 0;
}

The sum_digits() function returns summation of all digits on the input number n. It has a loop. In every iteration it gets the last digit by doing modulo operation by 10 (n%10) and adds that digit to sum. It removes the last digit by doing the div operation by 10. (n/10). The loop terminates when n becomes 0.

Here is the output of the program.

Enter an integer: 43652
Sum of all digits of 43652 is 20.

Recursive Version

Here is the recursive version of the same sum_digits() function.

int sum_digits(int n) {
    int rem = n%10;
    
    if(rem == 0) return n;
    return rem + sum_digits(n/10);
}

The post C Program to Find the Sum of all Digits of a Number appeared first on QnA Plus.


Viewing all articles
Browse latest Browse all 93

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>