Recursive function that sums the odd digits of an integer - c

For instance n = 8135267 => 16
Here is a solution but I don't understand it.
int sumOddDigits(int n) {
if(n == 0)
return 0;
if(n%2 == 1) //if n is odd
//returns last digit of n + sumOddDigits(n/10) => n/10 removes the last digit of n
return n % 10 + sumOddDigits(n/10)
else
return sumOddDigits(n/10);
}

Integer divison by ten "cuts off" the last digit: I.e. 1234/10 results in 123.
Modulo 10 returns the last digit: i.e. 1234%10 results in 4.
Thus, the above code considers always the last digit. If the last digit is odd (hence the %2==1 stuff) it will be counted, otherwise not. So, if it should count the digit, it takes the last digit (the % 10-stuff) and continues computing with the remaining digits (the recursion with the /10-stuff) and adding them to the digit. If the current digit shall not be counted, it continues just with the remaining digits (thus the recursion and the /10-stuff) without adding it to the current digit.
If the argument is 0, this means that the whole number is traversed, thus the function terminates with returning 0.

% is the modulo operator. It basically finds the remainder of dividing by a number.
n %2 n is only 1 if it's odd. % 10 gets the remainder of the dividing the number by 10, this gets you the currently last digit. Integer division by 10 gets you the next digit as the current last digit (1567/10 = 156)

Think about it this way: Starting with your known answer of 8135267 => 16, if I asked you for the sum of the odd digits in *3*8135267, what would you do? What if I asked for *4*8135267? How do your manual steps related to that function?

Think of it this way. If you get an even digit your function returns it + function value of the number without that digit. Otherwise it returns the function value of the number without the last digit. On your example:
813526(7) -> 0 + sumEvenDigits(813526)
6 + sumEvenDigits(81352)
2 + sumEvenDigits(8135)
....
8 + sumEvenDigits(0)
0 = 16
Hope this helps.

int sum_odd_digits(int n)
{
int s=0,r=0;
if(n==0)
return 0;
r = n%10;
if(r%2==1)
s = s+r;
n=n/10;
return s+ sum_odd_digits(n);
}

Related

return value meaning | pattern

What does the following function return? (in terms of meaning)
int f(int n){
if(n == 0) return 0;
else return n % 2 + f(n / 2)
}
Tried running the code, but couldn’t find any pattern in the results
This output of this function can be interpreted as the number of 1s (in base 10) when the number n is represented in binary.
The base case is when n == 0, where the number of 1s is 0.
For every other n, there is a recursive call. There are two parts to this. The first, which is n % 2, finds out the last bit of n. If it is a 1, it contributes to the value returned, and is hence, counted. The second part, f(n/2), is computing the number of 1s in all the bits of n except the last bit. This is because n/2 is n with a one bit right shift.
To put it together, the function works as follows. It checks the last bit, and if 1, it adds it to the total. It then performs a recursive call on itself with the last bit removed. This goes on till all bits are removed, which is covered by the base case.

Getting a certain digit from decimal in C

I have int x = 346.
I need to get in turn, each time a new digit of it, so first 3, then 4, then 6.
Using floor does not help me here,
and other examples here give only the left/right digit.
Is there a simple algorithm?
a%10 gives you the last digit of a number i.e. its remainder when divided by 10. You can print all the digits of a number like so:
void print_digits(int a) {
while (a > 0) {
printf("%d\n", a%10);
a /= 10;
}
}
This will print the digits from least significant to most significant. You can get them in reverse order if you use an auxiliary stack for instance.

getint() function multiply by 10?

I have a question about a part of the getint program.
When we got this part:
for(*pn = 0; isdigit(c); c = getch())
*pn = 10 * *pn + (c - '0');
First it converts c to its real numeric value, then it multiply the data inside pn with 10.
Why does it multiply 10 with the data inside pn?
Regards,
Ken
any number in the decimal notation can be expressed as a polynomial in 10
234 = 2*10^2 + 3*10 + 4
reading from the left and multiplying by 10 assures each digit ends up multiplying the correct power of 10. It's just an application of Horners rule, really.
It is starting from the left, and multiplying by 10 for each successive digit it encounters as it moves to the right.
Take the string "234" for example:
On the first iteration, take the 2. Multiply the 0 (*pn) by 10, add 2, you get 2.
On the second iteration, take the 3. Multiply the 2 (*pn) by 10, add 3, you get 23.
On the third iteration, take the 4. Multiply the 23 (*pn) by 10, add 4, you get 234.
The function is reading one digit at a time, starting from the left. So if it's reading, say, 12, then first it gets c == '1' and *pn == 0, it adds 1 to *pn and now *pn is 1. For each successive digit, it multiplies the existing value by ten (*pn is now 10) and adds the digit (*pn is now 12). This way it reads one digit at a time and ends up with the correct integer.

What does the condition "if (n/10)" with integral n specify?

I am looking at the following piece of code:
void printd(int n)
{
if (n < 0) {
putchar('-');
n = -n;
}
if (n / 10)
printd(n / 10);
putchar(n % 10 + '0');
}
I understand the first if statement fine, but the second one has me confused on a couple of points.
By itself, since "n" is an integer, I understand that n/10 will shift the decimal point to the left once - effectively removing the last digit of the number; however, I am having a little trouble understanding how this can be a condition by itself without the result being equal to something. Why isn't the condition if ((n/10) >= 0) or something?
Also, why is the '0' passed into the putchar() call?
Can someone tell me how it would read if you were to read it aloud in English?
Thanks!
The n / 10 will evaluate to false if the result is 0, true otherwise. Essentially it's checking if n > 10 && n < -10 (the -10 doesn't come into play here due to the n = -n code)
The + '0' is for character offset, as characters '0'-'9' are not represented by numbers 0-9, but rather at an offset (48-57 with ascii).
Can someone tell me how it would read if you were to read it aloud in English?
If you're talking about the conditional, then I would say "if integer n divided by 10 is not zero"
n/10 will not shift the decimal number since n is an integer. The division will produce the result like this: if n = 25, then n/10 would be 2 (without any decimal points), similarly if n = 9, then n/10 would be 0 in which case if condition would not be satisfied.
Regarding the +'0', since n%10 produces an integer result and in putchar you are printing a char , you need to convert the integer to a char. This is done by adding the ascii value of 0 to the integer.
In C, there is no separate boolean type; an expression like a > b evaluates to zero if false, non-zero if true. Sometimes you can take advantage of this when testing for zero or non-zero in an int.
As for the '0', that just performs character arithmetic so that the right character is printed. The zero character has an ASCII encoding value which isn't zero, so the n value is used as an offset from that encoding to get the right numeric digit printed out.

How can I iterate through each digit in a 3 digit number in C?

Length is always 3, examples:
000
056
999
How can I get the number so I can use the value of the single digit in an array?
Would it be easier to convert to an char, loop through it and convert back to int when needed?
To get the decimal digit at position p of an integer i you would do this:
(i / pow(p, 10)) % 10;
So to loop from the last digit to the first digit, you would do this:
int n = 56; // 056
int digit;
while(n) {
digit = n % 10;
n /= 10;
// Do something with digit
}
Easy to modify to do it exactly 3 times.
As Austin says, you can easily find answers on Google. But it basically involves mod-by-10, then divide-by-ten. Assuming integers.

Resources