finding 1st digit of an int using recursion

When I step thru my code its working, but then it spits out garbage! I don't know what I am doing wrong...
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
 int firstDigit(int NBR)
{
	
	if(NBR!=0)
	{
		
		
	 return	firstDigit(NBR/10);

		
	}

	


}


can you provide insite and an explanation as to how/why?
Your function has an undefined behaviour. I already showed in your first thread how to write such functions. What is the problem?
Last edited on
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..
@scthread

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.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <iostream>

int first_digit( unsigned int 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' ;
}

http://ideone.com/Q4Hzki
Wow! thank you for such a great explanation! I think i understand where I went wrong now.
Wondering if it wouldn't be easier to convert the number to a string and return the first char...
@ Smac89

That would probably be harder to do if you're a beginner.
Last edited on
Topic archived. No new replies allowed.