C program to add digits of a number: Here we are using modulus operator(%) to extract individual digits of number and adding them.
C programming code
If you wish you can modify input variable (n) and do not use an additional variable (t) but it is not recommended.
Output of program:
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.
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.
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 of program:
Add digits using recursion
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:
Post a Comment