This C program calculates the sum of the digits of a number.
Algorithm:
Extract the digits of the number and simply add them all, that’s it.
Code 1: C program to find sum of digits of a number
#include<stdio.h> int main() { int a,rem,sum= 0; printf("Enter a number: "); scanf("%d",&a); while(a!=0) { rem = a%10; a /= 10; sum += rem; } printf("\nSum of digits= %d\n",sum); return 0; }
Output:
Enter a number: 48295
Sum of digits= 28
Code 2: C program to find sum of digits of a four digit number without using loop
In this program, we will divide the number by 10, store the remainders and then we’ll multiply the remainders(digits) with proper multiples of 10 keeping place value in mind. Have a look at the code below:
#include<stdio.h> int main() { int a,b,c,d,sum; printf("Enter a four digit number: "); scanf("%d",&a); b=a%10; a/=10; c=a%10; a/=10; d=a%10; a/=10; sum= a + b + c + d; //finding sum printf("\nSum of digits= %d\n",sum); return 0; }
Output:
Enter a four digit number: 1974
Sum of digits= 21
We can find sum of digits of a number using for loop too. Below is the code.
Code 3: C program to find sum of digits of a number using for loop
#include<stdio.h> int main() { int a,rem,sum= 0; printf("Enter a number: "); scanf("%d",&a); for(; a!=0; a/=10) //you can skip initialization if nothing is needed to be initialized { rem = a%10; sum += rem; } printf("\nSum of digits= %d\n",sum); return 0; }
Output:
Enter a number: 379218
Sum of digits= 30
Now we will learn how to do the same thing using recursion.
Prerequisite knowledge:
- Everything discussed above and recursion.
Code 4: C program to find sum of digits of a number using recursion / recursive function
#include<stdio.h> int sumDig(int, int); int main() { int a,sum= 0; printf("Enter a number: "); scanf("%d",&a); sum = sumDig(a, sum); printf("\nSum of digits= %d\n",sum); return 0; } int sumDig(int num, int sum) { int rem; if(num!=0) { rem = num%10; sum +=rem; num /= 10; sumDig(num, sum); //recursion } else return sum; }
Output:
Enter a number: 813709
Sum of digits= 28
These are some ways to find the sum of digits of a number in C. Share this with programming beginners you know.
Basic C programming examples: C programs for practice
In this article, we learnt how to find:
- Sum of digits of a number in C using while loop.
- Sum of digits of a number in C using for loop.
- Sum of digits of a four digit number in C without using loop.
- Sum of digits of a number in C using recursion/recursive function.
If you know other ways to add the digits of a number, share your code in the comment section to help others.
You can learn this from this YouTube video: