![]() |
Add Digits of a Number in C Programming |
Hello guys, Welcome back to Standard Programming. Today I am going to show you how to add digits of a number given by the User. It's a very easy and popular problem in C. No matter which C Programming Book you follow, you will often find this problem in that book. So I decided to write a post on that to help those who are stuck in making the program.
The Logic
Here we will declare four variables.
- To contain the number given by the user
- To contain it in a temporary variable
- To calculate the Sum the of the digits
- To calculate the remainder
Let's see the code first then we will discuss each line individually.
#include <stdio.h> #include <conio.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); getch(); return 0; }
As I said we declare four variables called n,t,sum which is initialized to 0 and remainder. Then we copy the value of n to t and run a while loop till t !=0. In each Loop we will keep the last digit of the number in remainder variable by calculating the modulus of the number when divided by 10 and will add the to sum variable. And will divide the number by 10 to get the number containing one digit less.
As an example, if we take 123, first remainder will be 3 which will be added to sum resulting 3 as 0+3=3. Then we divide 123 by 10 which makes it 12 in the later loops. In the next loop remainder will carry the value 12%10= 2 and will be added to sum which already contains the value 3 and will yield the result 5. Similarly 1 will be added to sum and final result will be 6, 1+2+3=6 .
I hope the whole scenario is clear to you guys. But there is another method, use of Recursion by which you can add the digits of the Number.
Add Digits of Number with Recursion
#include <stdio.h> #include <conio.h> int add_digits(int); int main() { int n, result; scanf("%d", &n); result = add_digits(n); printf("%d\n", result); getch(); 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; }
I hope the above code of Recursion is quite simple and easy to under stand. We add the remainder and the number containing one less digit by Recursive Calls. If you have any problem with the code or need any further clarifications, don't hesitate to comment below. Thank you !
0 comments