Cant figure out a recursive function.

Recently took intro c++ class and learning recursion but im not sure how to approach this question. Any help would be appreciated.

Question: Implement a recursive function called firstTwo that returns the sum
of the first two digits in a positive number. If there is only one
digit, that digit is returned.
Note this function is returning an integer, not printing. There
should be no use of cout within your function.
Title line: int firstTwo(int n)
ex. firstTwo(8325) returns 11
ex. cout << firstTwo(428); // prints 6
Hint: (number % 10) will give you the right-most digit of that number (remainder). 1234 % 10 == 4
(number / 10) will give chop off the right-most digit of that number. 1234 / 10 == 123
Use these in combination to manipulate your data to get to the left-most and second-to-left-most digits.

That's probably the direction that assignments like these want you to go.
Last edited on
Recurse (by dividing by 10) until you get the first number < 100.

The digits of a 1- or 2-digit number have sum n / 10 + n % 10.
Yes, i understand the use of % and / and how they work. So far for cout << firstTwo(428); im getting 42 instead of 6. Im not sure what else i need to add.

Just for reference:

#include <iostream>
#include <cstring>
using namespace std;

int firstTwo(int n){
if(n < 10) return n;
if (n > 99)
return firstTwo(n / 10);
}
Change
if(n < 10) return n;
to
if ( n < 100 ) return ....
You fill in the blanks. Read my previous post.
I think i got it. Thank you so much.

int firstTwo(int n){
if(n < 100) return n / 10 + n % 10;
return firstTwo(n / 10);


}
Topic archived. No new replies allowed.