I didn't understand what you were coding - you use foreign syntax from what I have been taught... and my code above runs - w/out error - just produces bad output... so I don't understand why you say it has undefiend behavior?
when I step thru - it does it correctly - but for somereason it runs all the way thru till NBR=0 even though its not supposed to... and spits out -859883454 or some odd number, so I need to know how to make it stop when it gets to the first#.. and spit that out.
I am not a pro at this - I am only in my 2nd semester... so I am still learning and this whole recursion is messing my brain up..
I didn't understand what you were coding - you use foreign syntax from what I have been taught... and my code above runs - w/out error - just produces bad output...
The bad output means that the code is invalid that is it contains some errors. Errors can be of different kinds.
when I step thru - it does it correctly - but for somereason it runs all the way thru till NBR=0 even though its not supposed to... and spits out -859883454 or some odd number, so I need to know how to make it stop when it gets to the first#.. and spit that out.
Here you have an answer: what does your function return if NBR equals 0?
It should return something, you are not specific, so it returns garbage.
#include <iostream>
int first_digit( unsignedint number )
{
std::cout << "number: " << number << '\n' ;
if( number < 10 ) // the number consists of a single digit
{
std::cout << "there is just one digit, return it\n" ;
return number ; // just return that digit
}
// the number consists of two or more digits
// number/10 gives the number with the last (right-most) digit removed
return first_digit( number/10 ) ; // call recursively with one less digit
// each time through the recursion, we reduce the number of digits by one.
// Eventually, when there is just one digit left,
// that is the first (left-most) digit and we return that
}
int main()
{
std::cout << first_digit(12345678) << '\n' ;
}